Same-named attributes in attrs.xml for custom view
I'm writing a few custom views which share some same-named attributes. In their respective <declare-styleable>
section in attrs.xml
I'd like to use the same names for attributes:
<?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>
I'm getting an error saying that myattr1
and myattr2
are already defined. I found that I should omit the format
attribute for myattr1
and myattr2
in MyView2
, but if I do that, I obtain the following error in the console:
[2010-12-13 23:53:11 - MyProject] ERROR: In <declare-styleable> MyView2, unable to find attribute
Is there a way I could accomplish this, maybe some sort of namespacing (just guessing)?
Solution 1:
Solution: Simply extract common attributes from both views and add them directly as children of the <resources>
node:
<?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>
Solution 2:
I am posting this answer as the above-posted solution didn't work out for me in Android Studio. I need to share my custom attributes among my custom views so I tried the above solution in Android Studio but had no luck. So I experiment and go a way to do it. Hope it might help someone looking for the same problem.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- parent styleable -->
<declare-styleable name="MyView">
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
</declare-styleable>
<!-- inheriting parent styleable -->
<!-- also note "myBackgroundColor" belongs to child styleable"MyView1"-->
<declare-styleable name="MyView1" parent="MyView">
<attr name="myattr1" />
<attr name="myattr2" />
<attr name="myBackgroundColor" format="color"/>
</declare-styleable>
<!-- inheriting parent styleable -->
<!-- same way here "myfonnt" belongs to child styelable "MyView2" -->
<declare-styleable name="MyView2" parent="MyView">
<attr name="myattr1" />
<attr name="myattr2" />
<attr name="myfont" format="string"/>
...
</declare-styleable>
</resources>
This works for me completely. We need to make a Parent styleable and then we need to inherit that parent styleable. For example, as I have done above : Parent styleable name MyView and inherited this to my other styleable like MyView1 and MyView2 respectively.