You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

鸿蒙OS中对应Android TypedArray的替代方案是什么

HarmonyOS 自定义属性颜色值读取方案

Android平台通过TypedArray实现的自定义属性读取功能,在HarmonyOS中可通过AttrSet类配合ResourceManager实现,具体实现流程如下:

1. 定义自定义属性

在项目entry/src/main/resources/base/element/attr.xml中添加自定义属性声明,示例如下:

<declare-styleable name="CustomCalendarView">
    <attr name="calendarBackgroundColor" format="color"/>
    <attr name="titleLayoutBackgroundColor" format="color"/>
    <attr name="calendarTitleTextColor" format="color"/>
    <attr name="weekLayoutBackgroundColor" format="color"/>
</declare-styleable>

2. 自定义组件中读取属性值

在自定义组件的构造方法中直接通过AttrSet读取对应属性,无需手动回收资源,等价实现代码如下:

public CustomCalendarView(Context context, AttrSet attrSet) {
    super(context, attrSet);
    ResourceManager resourceManager = context.getResourceManager();
    // 读取日历背景色,默认值设置为白色
    int calendarBackgroundColor = attrSet.getAttr("calendarBackgroundColor").get()
            .getColorValue(resourceManager, Color.WHITE.getValue());
    // 读取标题栏背景色,默认值设置为白色
    int calendarTitleBackgroundColor = attrSet.getAttr("titleLayoutBackgroundColor").get()
            .getColorValue(resourceManager, Color.WHITE.getValue());
    // 读取标题文字颜色,默认值设置为黑色
    int calendarTitleTextColor = attrSet.getAttr("calendarTitleTextColor").get()
            .getColorValue(resourceManager, Color.BLACK.getValue());
    // 读取星期栏背景色,默认值设置为白色
    int weekLayoutBackgroundColor = attrSet.getAttr("weekLayoutBackgroundColor").get()
            .getColorValue(resourceManager, Color.WHITE.getValue());
}

注意事项

  • 读取属性前建议先判断属性是否存在,避免空指针异常:
    Optional<Attr> calendarBgAttr = attrSet.getAttr("calendarBackgroundColor");
    if (calendarBgAttr.isPresent()) {
        int color = calendarBgAttr.get().getColorValue(resourceManager, Color.WHITE.getValue());
    }
    
  • 鸿蒙AttrSet不需要像Android TypedArray一样调用recycle()方法回收,资源由系统自动管理
  • 如果你使用的是ArkTS方舟开发框架,可直接通过@Prop装饰器接收外部传入的自定义颜色属性,无需额外读取操作

内容的提问来源于stack exchange,提问作者Chakradhar Chokkaku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 03:51:01