ohos扩展包——工具集合

jacksky
发布于 2021-9-29 18:26
1.2w浏览
0收藏

工具类

  • onSaveAbilityState/onRestoreAbilityState分发 StateHelper

StateHelper

将onSaveAbilityState/onRestoreAbilityState分发给Ability内所有的Component

使用

在Ability内调用:

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        StateHelper.saveState(this, outState);
    }

    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        StateHelper.restoreState(this, inState);
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

在需要save/restore的控件内,实现SaveRestoreState接口:

public class ViewPager extends ComponentContainer implements SaveRestoreState {
        @Override
        public void onSaveState(PacMap state) {
            state.putIntValue("position", mCurItem);
            if (mAdapter != null) {
                state.putPacMap("adapterState", mAdapter.saveState());
            }
        }
    
        @Override
        public void onRestoreState(PacMap state) {
            if (mAdapter != null) {
                Optional<PacMap> adapterState = state.getPacMap("adapterState");
                if (adapterState.isPresent()) {
                    mAdapter.restoreState(adapterState.get(), null);
                } else {
                    mAdapter.restoreState(null, null);
                }
    
                setCurrentItemInternal(state.getIntValue("position"), false, true);
            } else {
                mRestoredCurItem = state.getIntValue("position");
                mRestoredAdapterState = state.getPacMap("adapterState").get();
                mRestoredClassLoader = null;
            }
        }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

 

 

  • 替换自定义控件中的Gravity Gravity

Gravity

替换安卓中的Gravity与GravityCompact类

使用

与安卓一致,替换即可

 

  • 测量帮助类 EstimateHelper

EstimateHelper

测量帮助类,提供一些通用的测量方法

使用

根据size与mode生成EstimateSpec,与安卓的MeasureSpec.makeMeasureSpec(int size, int mode)实现一致

EstimateHelper.makeEstimateSpec(size, mode);
  • 1.

根据父component的spec、padding以及子component的期望大小,生成子component的spec。与安卓中ViewGroup.getChildMeasureSpec(int spec, int padding, int childDimension)实现一致

EstimateHelper.getChildMeasureSpec(parentSpec, padding, childSize);
  • 1.

决定控件的大小,除非有特别的约束,否则会返回控件想要的大小。与安卓中View.resolveSize(int size, int measureSpec)实现基本一致

EstimateHelper.resolveSizeAndState(size, measureSpec);​
  • 1.

获取控件的默认大小,除非有特别的约束,否则会返回控件想要的大小。与安卓中View.getDefaultSize(int size, int measureSpec)实现一致

EstimateHelper.getDefaultSize(size, measureSpec);
  • 1.

 

  • 网格布局的ItemProvider EasyGridProvider

EasyGridProvider

实现网格布局的ItemProvider

自定义Provider继承EasyGridProvider

public class MyBaseQuickAdapter extends EasyGridProvider<UserViewInfo> {

    public MyBaseQuickAdapter(Context mContext) {
        super(mContext);
    }

    @Override
    protected void bind(ViewHolder holder, UserViewInfo item, int position) {
        Image thumbView = holder.getView(ResourceTable.Id_iv);
        iv.setVisibility(Component.VISIBLE);
        
    }

    @Override
    protected void bindPlaceholder(ViewHolder holder, int position) {
        Image iv = holder.getView(ResourceTable.Id_iv);
        iv.setVisibility(Component.HIDE);
    }

    @Override
    protected int getLayoutId() {
        return ResourceTable.Layout_item_image_grid;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

布局文件

<?xml version="1.0" encoding="utf-8"?>
<DependentLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    >

    <Image
        ohos:id="$+id:iv"
        ohos:height="match_parent"
        ohos:width="match_parent"
        />
</DependentLayout>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

ListContainer设置适配器

  ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_listView);
  MyBaseQuickAdapter myBaseQuickAdapter = new MyBaseQuickAdapter(this);
  //设置数据
  myBaseQuickAdapter.setData();
  //设置网格数
  myBaseQuickAdapter.setNumColumns(2);
  //设置网格间隙
  myBaseQuickAdapter.setGridSpacing(0);
  //设置点击事件
  listContainer.setItemProvider(myBaseQuickAdapter);
  myBaseQuickAdapter.setOnItemClickListener(new EasyGridProvider.OnItemClickListener() {
      @Override
      public void onItemClick(Component component, int position) {

      }
  });
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

横竖屏切换

 protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
    super.onOrientationChanged(displayOrientation);
    myBaseQuickAdapter.updateDisplayWidth(displayOrientation);
    myBaseQuickAdapter.notifyDataChanged();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

  • 颜色平滑渐变 ArgbEvaluator

ArgbEvaluator

两个颜色之间平滑渐变的动画工具类,配合AnimatorValue一起使用。

ohos扩展包——工具集合-鸿蒙开发者社区

使用

button.setClickedListener(component1 -> {
    AnimatorValue animatorValue = new AnimatorValue();
    animatorValue.setValueUpdateListener((animatorValue1, fraction) -> {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt((Integer) ArgbEvaluator.getInstance().evaluate(fraction, Color.WHITE.getValue(), Color.BLACK.getValue())));
        button.setBackground(element);
    });
    animatorValue.setDuration(5000);
    animatorValue.start();
});
```
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

 

 

  • 防重复点击 PreventRepeatUtils

PreventRepeatUtils

确保按钮一秒内只能执行一次click事件

使用

button.setClickedListener(component1 -> {
    PreventRepeatUtils.preventRepeatClick(() -> {
        //do something
    });
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

 

  • 线程池管理 ThreadPoolManager

ThreadPoolManager

线程池管理类

使用

ThreadPoolManager.getExecutor().execute();//启动

ThreadPoolManager.getExecutor().shutDown();//关闭线程

ThreadPoolManager.getExecutor().shutdownNow();//尝试停止所有正在执行的任务,停止正在等待的任务的处理,并返回正在等待执行的任务的列表
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

  • 设置壁纸 ApplyWallpaperAsyncTask

ApplyWallpaperAsyncTask

设置壁纸任务

使用

Java:
new ApplyWallpaperAsyncTask(MainAbility.this, new File("imageFilePath"), new ApplyWallpaperAsyncTask.ApplyWallpaperListener() {
    // isSuccess 设置壁纸回调, true:设置壁纸成功; false:设置壁纸失败
    @Override
    public void onApplyWallpaperSuccessed(boolean isSuccess) {

    }
}).execute();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
config.json:
{
    "name": "ohos.permission.SET_WALLPAPER",
    "reason": "设置壁纸"
}
  • 1.
  • 2.
  • 3.
  • 4.

 

  • 水波纹 RippleUtil

RippleUtil

给组件设置触摸水波纹效果

ohos扩展包——工具集合-鸿蒙开发者社区

使用

调用setComponent系列函数:

RippleUtil.setComponent(component, 5, 0xAAAAAA);
  • 1.
  • 2.
  • 3.

注意

由于组件的setTouchEventListener只能设置一次,后设置的会替换前面的,可能会导致原有的TouchEventListener失效

 

  • ColorStateList

ColorStateList

替换Android中的ColorStateList

 

  • 查找Component FindViewUtil

FindViewUtil

查找视图工具类

使用

FindViewUtil.getTargetView(parent, ResourceTable.Id_text);
FindViewUtil.getTargetView(parent, Text.class);
FindViewUtil.getTargetView(parent, Text.class, ResourceTable.Id_text);
  • 1.
  • 2.
  • 3.
  • 状态栏、导航栏等相关 WindowUtil

WindowUtil

Window相关工具

使用

  1. 获取状态栏高度、隐藏状态栏
    WindowUtil.getStatusBarHeight(getContext());
    WindowUtil.getStatusBarHeightInPixels(getContext());
    WindowUtil.hideStatusBar(getWindow(), true);​
    • 1.
    • 2.
    • 3.
  2. 获取底部导航栏高度、底部导航栏是否显示
    WindowUtil.getNavigationHeightInPixels(getContext());
    WindowUtil.isHideNavigationBar(root);​
    • 1.
    • 2.
  3. 获取纵横比,判断是否是全面屏
    WindowUtil.getAspectRatio(getContext());
    WindowUtil.isFullScreenDevice(root);​
    • 1.
    • 2.
  4. 获取屏幕宽高
    WindowUtil.getWindowWidth(getContext());
    WindowUtil.getWindowHeight(getContext());​
    • 1.
    • 2.

 

  • AttrSet获取自定义属性工具类 AttrUtils

AttrUtils

从AttrSet获取自定义属性工具类

使用

xxx extends Component

从AttrSet获取自定义属性:传入 AttrSet,属性名,默认值

String count = AttrUtils.getInteger(attrSet,"cus_count","0");

属性定义:

布局头中加入 xmlns:hap="http://schemas.huawei.com/apk/res/ohos" ,使用hap区分自定义属性与系统属性。

即可使用hap:cus_count="2",不加直接使用ohos:cus_count="2"

AttrUtils.getInteger();//获取int类型属性值

AttrUtils.getString();//获取string类型属性值

AttrUtils.getFloat();//获取float属性值

AttrUtils.getBoolean();//获取boolean类型属性值

AttrUtils.getColorInt();//获取int color类型属性值

AttrUtils.getColorObj();//获取color 类型属性值 返回Color对象

AttrUtils.getLong();//获取long类型属性值

AttrUtils.getDimensionValue();//获取int 类型属性值

AttrUtils.getElement();//获取Element类型属性值
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

  • 主线线程和子线程间的切换 HiExecutor

HiExecutor

主线线程和子线程间的切换

使用

HiExecutor.runUI(runnable);//切换任务到主线程执行
HiExecutor.runBG(runnable);//切换到子线程执行任务
  • 1.
  • 2.

 

  • 通过资源id获取对应资源类型值 ResUtil

ResUtil

ResourceTable资源工具类,通过资源id获取对应资源类型值

使用

ResUtil.getColor(Context context, int id);//根据color id获取color int值

ResUtil.getColorObj()//根据资源color id获取color 对象

ResUtil.getFloat();//根据资源id获取 float 类型值

ResUtil.getBoolean();//根据资源id获取 boolean 类型值

ResUtil.getString();//根据资源id获取 String 类型值

ResUtil.getStringArray() ;//根据资源id获取 string array 类型值

ResUtil.getInt() ;//根据资源id获取 int 类型值

ResUtil.getIntArray() ;//根据资源id获取 int array 类型值

ResUtil.getPathById() ;//通过资源ID获取资源路径

ResUtil.getVectorDrawable() ;//根据资源id获取 VectorElement

ResUtil.getPixelMap() ;//根据资源id获取 PixelMap

ResUtil.getShapeElement() ;//创建 ShapeElement

ResUtil.getPixelMapDrawable() ;//根据资源id 获取PixelMapElement

ResUtil.getCustomArcGradientDrawable() ;// 创建ShapeElement 弧形渐变

ResUtil.getPixelMapScaled() ;// 通过资源id获取PixelMap 并根据屏幕密度进行缩放
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • Element着色器 ImageTint

ImageTint

Element着色器

使用

示例

Image image = (Image) findComponentById(ResourceTable.Id_image);
ShapeElement shapeElement = new ShapeElement();
shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#FF55E33C")));

Element element = ImageTint.getTintElement(shapeElement, Color.getIntColor("#6AE33CBF"));
image.setImageElement(element);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

主要方法

ImageTint.getTintElement();//获取着色后的Element
ImageTint.setImageTint();//直接给Image设置着色后的Element
  • 1.
  • 2.

 

颜色相关工具类 ColorUtil

ColorUtil

颜色相关工具类

使用数据

String COLOR = "#3F51B5";
int argb = Color.argb(255, 63, 81, 181);
int rgb = Color.rgb(63, 81, 181);
  • 1.
  • 2.
  • 3.

使用说明

1) adjustAlpha(float alpha, int color) 改变颜色透明度数值

alpha:透明度 (0.1-1.0)
color:颜色色值
  • 1.
  • 2.

示例代码:

int color = ColorUtil.adjustAlpha(0.1f, Color.getIntColor(COLOR));
  • 1.

2) getAlphaPercent(int argb) 获取ARGB颜色的透明度百分比数值

argb:ARGB颜色(int argb = Color.argb(255, 0, 155, 95))
  • 1.

示例代码:

float alphaPercent = ColorUtil.getAlphaPercent(argb);
  • 1.

3) colorAtLightness(int color, float lightness) 改变颜色的亮度数值

color:颜色色值
lightness:亮度值
  • 1.
  • 2.

示例代码:

int color = ColorUtil.colorAtLightness(Color.getIntColor(COLOR), 0.5f);
  • 1.

4) lightnessOfColor(int color) 获取颜色亮度数值(传入的颜色为RGB格式返回的lightness即为G值)

color:颜色色值
  • 1.

示例代码:

float lightness = ColorUtil.lightnessOfColor(argb);
  • 1.

5) isHexString(int color, boolean isShowAlpha) Color转十六进制格式

color:颜色色值
isShowAlpha:返回值是否展示透明度
  • 1.
  • 2.

示例代码:

   String colorHex = ColorUtil.isHexString(Color.getIntColor(COLOR), true);    
    colorHex = "#3F51B5"
    String colorHex = ColorUtil.isHexString(Color.getIntColor(COLOR), false);  
    colorHex = "#FF3F51B5"
  • 1.
  • 2.
  • 3.
  • 4.

6) rgbToHsv(double rr, double gg, double bb) RGB格式转HSV格式

rr:RGB格式的red色值
gg:RGB格式的green色值
bb: RGB格式的blue色值
  • 1.
  • 2.
  • 3.

示例代码:

double[] colorHsv = ColorUtil.rgbToHsv(63, 81, 181);
  • 1.

7) hsvToRgb(float[] hsv) HSV格式转RGB格式

hsv:HSV格式色值
  • 1.

示例代码:

float[] colorRgb = ColorUtil.hsvToRgb(shv);
  • 1.


8) hexToRgb(String hex) 十六进制格式转RGB格式

hex:十六进制格式色值
  • 1.


示例代码:

int[] colorRgb = ColorUtil.hexToRgb(COLOR);
  • 1.


9) hexToColor(String hex) 十六进制格式转Color格式

hex:十六进制格式色值
  • 1.


示例代码:

int color = ColorUtil.hexToColor(COLOR);
  • 1.


10) getHexString(int color) Color格式转十六进制格式

color:颜色色值
  • 1.


示例代码:

String colorHex = ColorUtil.getHexString(Color.getIntColor(COLOR));
  • 1.


11) colorToRgb(int color) Color格式转RGB格式

color:颜色色值
  • 1.


示例代码:

int[] colorRgb = ColorUtil.colorToRgb(Color.getIntColor(COLOR));
  • 1.

已于2021-9-29 18:26:15修改
3
收藏
回复
举报
3
1
1条回复
按时间正序
/
按时间倒序
wx625643bb53348
wx625643bb53348

哥儿,工具类地址方便贴一下吗,这只有使用方法没有代码呀。

回复
2022-4-21 16:21:08


回复
    相关推荐