我最终得到的解决方案是pskink在评论中建议的解决方案:自己解析attrs.xml
和提取值。
有两个原因使得这样做是完全合理的:
- 我需要这个进行单元测试(要了解更多信息,请在问题下的评论中阅读我与pskink的对话)。
- 对名称/值不存储在任何地方。仅
ints
在使用时使用AttributeSet
。
我最终得到的代码是这样的:
public final class AttrsUtils {
private static final String TAG_ATTR = "attr";
private static final String TAG_ENUM = "enum";
private static final String ATTRIBUTE_NAME = "name";
private static final String ATTRIBUTE_FORMAT = "format";
private static final String ATTRIBUTE_VALUE = "value";
@CheckResult
@NonNull
public static Map<String, Integer> getEnumAttributeValues(String attrName)
throws ParserConfigurationException, IOException, SAXException {
final File attrsFile = new File("../app/src/main/res/values/attrs.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(attrsFile);
doc.getDocumentElement().normalize();
Map<String, Integer> fontAttributes = new ArrayMap<>();
NodeList nList = doc.getElementsByTagName(TAG_ATTR);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node attrNode = nList.item(temp);
if (attrNode.getNodeType() == Node.ELEMENT_NODE) {
Element attrElement = (Element) attrNode;
final String name = attrElement.getAttribute(ATTRIBUTE_NAME);
if (!attrElement.hasAttribute(ATTRIBUTE_FORMAT) || !name.equals(attrName)) {
continue;
}
final NodeList enumNodeList = attrElement.getElementsByTagName(TAG_ENUM);
for (int i = 0, size = enumNodeList.getLength(); i < size; ++i) {
final Node enumNode = enumNodeList.item(i);
if (enumNode.getNodeType() == Node.ELEMENT_NODE) {
Element enumElement = (Element) enumNode;
fontAttributes.put(
enumElement.getAttribute(ATTRIBUTE_NAME),
Integer.parseInt(enumElement.getAttribute(ATTRIBUTE_VALUE)));
}
}
break; // we already found the right attr, we can break the loop
}
}
return fontAttributes;
}
// Suppress default constructor for noninstantiability
private AttrsUtils() {
throw new AssertionError();
}
}
此方法返回一个Map
of name
- value
pairs 表示具有 的属性attrName
。
对于我在问题中写的示例,您可以像这样使用此方法:
Map<String, Integer> enumAttr = AttrsUtils.getEnumAttributeValues("my_custom_enum");