declare-styleable attr 重命导致的报错:
Attribute *** has already been defined
1:项目中出现 Attribute *** has already been defined
同一个attr.xml 文件定义了下面的属性
<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:重命名相同属性名,将其中一个改为不同的名字,如改成custom1
<attr name="custom1" />
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>
c:放在2个不同attr.xml文件中也可以解决,如定一个attrs.xml 文件(与前一个文件名不同就行),注:attrs.xml 可以放同一个项目中,也可以放不同的项目中(作为库工程),不影响结果。