对于以下示例,我使用的视图标记如下所示:
<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="this is the hint"
android:text="@string/dummy_content"
android:textColor="?colorAccent" />
android:hint
是纯文本,
android:text
是资源属性,并且
android:textColor
是样式属性。
AttributeSet.getAttributeValue()
. 对于纯文本属性,这将为您提供实际值(例如
这是回报
"this is the hint"
资源属性返回一个以
@
这是回报
"@2131689506"
). 然后可以解析这个字符串的数字部分并使用
Resources.getResourceName()
获取解析名称(
"com.example.stackoverflow:string/dummy_content"
样式属性返回以
?
android:textColor
这是回报
"?2130903135"
). 但是,我不知道有什么方法可以用支持的api将这个数字转换成文本表示。不过,希望这足以帮助其他人找到完整答案。
使用反射
但是,如果您愿意偏离轨道,可以使用反射来查找style属性的文本值。因为字符串以
R.attr
或
android.R.attr
. 您可以使用如下代码扫描这些字段以查找匹配的字段:
private static String scan(Class<?> classToSearch, int target) {
for (Field field : classToSearch.getDeclaredFields()) {
try {
int fieldValue = (int) field.get(null);
if (fieldValue == target) {
return field.getName();
}
} catch (IllegalAccessException e) {
// TODO
}
}
return null;
}
int id = Integer.parseInt(attributeValue.substring(1));
String attrName = scan(R.attr.class, id);
String androidAttrName = scan(android.R.attr.class, id);
对我来说,这将输出
colorAccent
null
如果
android:textColor
是
?android:colorAccent
?colorAccent
,则输出为:
null
colorAccent