most of you will know that there is a possibility to give custom Attributes to custom Views in Android. This is explained quite brilliantly for example in this thread here on Stackoverflow. My question however is:
Is it possible to present such attributes only upon fulfillment of another condition?
What I mean by that is something like this (Pseudo-code):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="isClock" format="boolean" />
</declare-styleable>
<if name="isClock" value="true">
<attr name="timezone" format="string">
</if>
<else>
<attr name="somethingElse" format="string>
</else>
</resources>
Now one possibility to not have to work with "wrong" attributes is to do this in the Java-Code, obviously:
public class MyCustomView {
public MyCustomView(Context context) {
TypedArray styleables = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
boolean choice = styleables.getBoolean(R.styleable.MyCustomView_isClock, false);
if(choice) {
// It's a clock, react to the other attrs
} else {
// Don't react
}
styleables.recycle();
}
}
Another way would be to do what ilomambo suggested in his answer: create various custom views with different names and let them only have the attributes that belong to them.
But I'm very much asking myself if it's possible to not confuse the programmer of the .xml-File in the first place and offer him only the stuff he really needs combined in one place. After all this is in a way already done by Android (well... the IDE/Lint/the Parser...) when hinting for example that the width or height of a view should be set to 0dp
when using layout_weight
.
But if I had to guess I'd say it's probably only possible if I rewrite the Android XML-Parser... Can someone please prove me wrong?
Thanks in advance