问题
Is it possible to reference an enum value when supplying style parameters?
For example, we can do:
<!-- layouts.xml -->
<TextView
android:text="@string/str" />
<!-- values.xml -->
<item type="string" name="str">hi</item>
This works fine with strings, integers, dimensions and so on but I need to reference an enum value - for example the visibility
attribute. I'm looking for something like:
<!-- layouts.xml -->
<TextView
android:visibility="@????/viz" />
<!-- values.xml -->
<item type="?????" name="viz">gone</item>
visibility
is only an example - it could be any other enum based attribute.
The only workaround I have found so far is by using styles
<!-- layouts.xml -->
<TextView
android:style="@styles/theStyle" />
<!-- styles.xml -->
<style name="theStyle">
<item name="android:visibility">gone</item>
</style>
But this is somehow restrictive because it becomes increasingly complicated if you need to use real styles with the TextViews and this special style which is only used to control a single attribute.
Another option would be if there is a way to reference individual style items. Something like:
<TextView
android:visibility="@styles/theStyle/visibility" />
But I think that the above is even less likely to be possible.
回答1:
Each enum is actually a set of named integers.
For example, visibility
attribute is declared as follows:
<attr name="visibility">
<enum name="visible" value="0" />
<enum name="invisible" value="1" />
<enum name="gone" value="2" />
</attr>
So you can reference to enum item directly by its value. Something like this:
<!-- values.xml -->
<item name="viz" type="integer">1</item>
<!-- layouts.xml -->
<TextView
android:visibility="@integer/viz"/>
I just checked it on my phone and it works well.
来源:https://stackoverflow.com/questions/14176563/reference-attribute-enum-value