gpt4 book ai didi

android - 如何从 AttributeSet 中获取属性的原始未解析值?

转载 作者:行者123 更新时间:2023-11-29 00:58:59 24 4
gpt4 key购买 nike

我正在尝试找到一种方法来获取属性的原始未解析值。就此而言,我指的是布局文件中几乎完全相同的文本,而无需直接解析文件。

假设有一个像这样的 TextView:

<TextView
...
android:textColor="?colorAccent"
/>

我希望能够将 "?colorAccent" 作为字符串或值的条目名称 (如 package:attr/colorAccent ).

没有 XMLPullParser 这可能吗?

最佳答案

对于这些示例,我正在使用如下所示的 View 标签:

<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() 开始。对于纯文本属性,这将为您提供实际值(例如,对于 android:hint,这将返回 “this is the hint”)。

资源属性返回一个字符串,该字符串以 @ 开头,然后是一个数字(例如,对于 android:text,它返回 "@2131689506").然后,您可以解析此字符串的数字部分并使用 Resources.getResourceName() 获取已解析的名称 ("com.example.stackoverflow:string/dummy_content")。

样式属性返回一个以 ? 开头然后是数字的字符串(例如对于 android:textColor 返回 "?2130903135" ).但是,我不知道有什么方法可以将此数字转换为支持 API 的文本表示形式。不过,希望这足以帮助其他人获得完整答案。

使用反射

不过,如果您愿意偏离轨道,则可以使用反射来查找样式属性的文本值。因为字符串以 ? 开头,所以您知道它在 R.attrandroid.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

关于android - 如何从 AttributeSet 中获取属性的原始未解析值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com