Andorid自定义attr的各种坑

在开发Andorid应用程序中,经常会自定义View来实现各种各样炫酷的效果,在实现这吊炸天效果的同时,我们往往会定义很多attr属性,这样就可以在XML中配置我们想要的属性值,以下就是定义属性值可能遇到的各种坑。

大家都知道怎么定义attr属性,一般如下:

<declare-styleable name="Sample">
   <attr name="custom" format="string|reference" />
</declare-styleable>

先声明一个styleable名称,name名称最好见名知义,一个styleable里面可以有多个attr属性,每一个attr都含有一个name,同时需要指明所能赋值的类型,这是是依靠format来定义的。定义好之后就可以在自定义View中使用,来实现各种吊炸天的效果,使用如下:
xml中使用:

<com.sample.ui.widget.Custom
   android:id="@+id/custom_view"
   android:layout_width="130dp"
   android:layout_height="130dp"
   android:layout_gravity="center_horizontal"
   android:layout_marginTop="90dp"
   app:custom="@string/custom_desc"
   />

记得声明 xmlns:app=”http://schemas.android.com/apk/res-auto”, app 可以随便取名
代码中获取值:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Sample);
String value = a.getString(R.styleable.Sample.custom);
a.recycle();

根据format不同,还有getDimension,getColor等方式获取值。

上面只是描述了一般定义的方式,但他不是今天的主题,今天的主题是可能遇到的各种坑:

1:项目中只包含一个attr.xml,出现 Attribute “custom” has already been defined,参考链接

<declare-styleable name="Sample">
        <attr name="custom" format="string|reference" />
</declare-styleable>

<declare-styleable name="Sample1">
        <attr name="custom" format="string|reference" />
</declare-styleable>

如上声明了两个styleable,同时包含了相同的属性custom,这时在编译时会提示Attribute “xxx” has already been defined,表示相同属性重复定义,相同styleable name不能再同一个attr.xml中重复定义,styleable name不一致attir也不能重复定义,attr format属性不影响重复定义结果。因此可以采用如下方法解决该问题:

a:重命名相同属性名,将其中一个改为不同的名字
b:提取重复定义attr,作为公共属性,方式如下:

<attr name="custom" format="string|reference" />

<declare-styleable name="Sample">
    <attr name="custom" />
</declare-styleable>

<declare-styleable name="Sample1">
    <attr name="custom" />
</declare-styleable>

2: 项目中引用了多个外部项目,出现 Attribute “custom” has already been defined
不同的导入项目中,可能包含多个attr.xml,这样在定义时极有可能重复定义,他又分为如下两种情况:

a: 主项目,引用库包含同名styleable name,如:
主项目:

<declare-styleable name="Sample">
    <attr name="custom" />
</declare-styleable>

引用库:

<declare-styleable name="Sample">
    <attr name="custom" />
</declare-styleable>

这种情况下,编译是不会出现错误的,可以正常编译。

b: 主项目,引用库包含不同名styleable,但是有同名attr,如;
主项目:

<declare-styleable name="Sample">
    <attr name="custom" />
</declare-styleable>

引用库:

<declare-styleable name="Sample1">
    <attr name="custom" />
</declare-styleable>

编译时会出现 Attribute “custom” has already been defined。由此可以得出,在项目中引用各种库,模块时,各个不同的模块定义attr,要遵循以下规则,
1:全部不能重复定义,全部不能重复很难实现,不同的团队,不同的产品是极有可能重复定义,因此该方式很难实现。
2:各个不同模块,定义时加上模块前缀,这种方式重复几率就小很多,编译时再将重复的重命名就ok了。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值