我正在编写一些共享一些同名属性的自定义视图。在他们各自的<declare-styleable>部分中,attrs.xml我想为属性使用相同的名称:
<declare-styleable>
attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView1"> <attr name="myattr1" format="string" /> <attr name="myattr2" format="dimension" /> ... </declare-styleable> <declare-styleable name="MyView2"> <attr name="myattr1" format="string" /> <attr name="myattr2" format="dimension" /> ... </declare-styleable> </resources>
我收到一条错误消息,myattr1并且myattr2已经定义。我发现我应该省略format属性 formyattr1和myattr2in MyView2,但如果这样做,我会在控制台中获得以下错误:
myattr1
myattr2
format
MyView2
[2010-12-13 23:53:11 - MyProject] ERROR: In <declare-styleable> MyView2, unable to find attribute
有没有办法我可以做到这一点,也许是某种命名空间(只是猜测)?
解决方案: 简单地从两个视图中提取公共属性,并将它们直接添加为节点的子<resources>节点:
<resources>
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="myattr1" format="string" /> <attr name="myattr2" format="dimension" /> <declare-styleable name="MyView1"> <attr name="myattr1" /> <attr name="myattr2" /> ... </declare-styleable> <declare-styleable name="MyView2"> <attr name="myattr1" /> <attr name="myattr2" /> ... </declare-styleable> </resources>