gpt4 book ai didi

java - 如何获取枚举自定义属性的所有可能值?

转载 作者:行者123 更新时间:2023-12-01 09:00:10 24 4
gpt4 key购买 nike

假设我的 View 有一个自定义属性 my_custom_enum:

<attr name="my_custom_enum" format="enum">
<enum name="first_value" value="751"/>
<enum name="second_value" value="2222"/>
<enum name="third_value" value="1241"/>
<enum name="fourth_value" value="4"/>
</attr>

<declare-styleable name="CustomViewOne">
<attr name="my_custom_enum"/>
</declare-styleable>

<declare-styleable name="CustomViewTwo">
<attr name="my_custom_enum"/>
</declare-styleable>

有没有办法在代码中获取此枚举的所有可能的值

换句话说:

我希望有一种方法来获取值751222212414。这些值的名称也很好,但不是强制性的。

最佳答案

我最终得到的解决方案是 pskink 建议的解决方案在 comment :自己解析 attrs.xml 并提取值。

有两个原因使得这样做完全合理:

  1. 我需要这个来进行单元测试(要了解更多信息,请在问题下的评论中阅读我与 pskink 的对话)。
  2. 名称/值对不存储在任何地方。使用 AttributeSet 时仅使用 int

我最终得到的代码是这样的:

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();
}
}

此方法返回 name-value 对的 Map,这些对表示具有 attrName 的属性。

<小时/>

对于我在问题中编写的示例,您可以像这样使用此方法:

Map<String, Integer> enumAttr = AttrsUtils.getEnumAttributeValues("my_custom_enum");

关于java - 如何获取枚举自定义属性的所有可能值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41740725/

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