dhulihan
dhulihan

Reputation: 11303

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

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/setters like View.getText()... I'm just wondering if there's a way to grab an xml attribute right from the item itself.

Upvotes: 5

Views: 10491

Answers (3)

Al Sutton
Al Sutton

Reputation: 3924

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).

Upvotes: 2

Primal Pappachan
Primal Pappachan

Reputation: 26535

<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.

Upvotes: 1

ognian
ognian

Reputation: 11541

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

Upvotes: 1

Related Questions