开发者

Android: Get an attribute's value from an XML item

开发者 https://www.devze.com 2023-01-05 16:55 出处:网络
Is there an easy way to grab a attribute value from an xml item in your Java class definition? I\'m looking for something like this:

Is there an easy way to grab a attribute value from an xml item in your Java class definition? I'm looking for something like this:

// In xml layout:

<TextView android:id="@+id/MyXMLitem" android:textColor="#000000" /> 

// in Java Class definition

String some_text_color;
some_text_color = R.id.MyXMLitem.attr.textColor; // I'd like this to return "#000000"

I know you can grab similar xml attributes from the converted objects using getters/开发者_Python百科setters like View.getText()... I'm just wondering if there's a way to grab an xml attribute right from the item itself.


Views take the XML values and store them into class level variables in their constructors so it's not possible to get values from the object itself once the layout has been created.

You can see this in the source of the View object at https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java if you search for AttributeSet (which is the object used to pass the XML layout values to the constructor).


You can use XmlResourceParser to read data straight from XML resources.


<TextView android:id="@+id/MyXMLitem" android:textColor="#000000" /> 

You can use getCurrentTextColor().

TextView tv = (TextView)findViewbyId(R.id.MyXMLitem);

String color = Integer.toHexString(tv.getCurrentTextColor());

It returns ff000000 instead of #000000 though.

0

精彩评论

暂无评论...
验证码 换一张
取 消