The solution I ended up with is the one suggested by pskink in the comment: parsing the attrs.xml
and extracting values myself.
There are two reasons that made it perfectly reasonable to do it this way:
- I need this for a Unit Test (to know a bit more about that, read my conversation with pskink in comments under the question).
- Pairs name/value are not stored anywhere. Only
ints
are used when using AttributeSet
.
The code I ended up with is this:
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();
}
}
This method returns a Map
of name
-value
pairs that represent an attribute that has attrName
.
For the example I wrote in the question, you would use this method like this:
Map<String, Integer> enumAttr = AttrsUtils.getEnumAttributeValues("my_custom_enum");