·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> Andorid自定义attr的各种坑

Andorid自定义attr的各种坑

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

在开发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:text="@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了。

以上就是本文的全部内容,希望对大家的学习有所帮助。