是否有一种从Java类定义中的xml项中获取属性值的简单方法?我正在寻找这样的东西:
//在xml布局中:
<TextView android:id="@+id/MyXMLitem" android:textColor="#000000" />
//在Java类定义中
String some_text_color;
some_text_color = R.id.MyXMLitem.attr.textColor; // I'd like this to return "#000000"
我知道你可以使用像get.getText()这样的getter / setter从转换的对象中获取类似的xml属性......我只是想知道是否有一种方法可以直接从项目本身获取xml属性。
答案 0 :(得分:2)
视图采用XML值并将它们存储到构造函数中的类级变量中,因此一旦创建了布局,就无法从对象本身获取值。
您可以在https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java的View对象的源代码中看到这一点 如果搜索AttributeSet(用于将XML布局值传递给构造函数的对象)。
答案 1 :(得分:1)
<TextView android:id="@+id/MyXMLitem" android:textColor="#000000" />
您可以使用getCurrentTextColor()。
TextView tv = (TextView)findViewbyId(R.id.MyXMLitem);
String color = Integer.toHexString(tv.getCurrentTextColor());
它返回 ff000000 而不是#000000 。
答案 2 :(得分:1)
您可以使用XmlResourceParser直接从XML资源中读取数据。