tags:

views:

57

answers:

3

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.

+1  A: 
<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.

primalpop
Very cool, this is one of the implementations I was looking for.
Hulihan Applications
+1  A: 

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 http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=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).

Al Sutton
Thanks Al - I wasn't sure if there was native Android functionality that would grab a xml attribute value right from an layout file. Now I know!
Hulihan Applications
A: 

Hi,

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

ognian