【发布时间】:2015-09-19 16:39:26
【问题描述】:
我有想要在视图中使用的资源。
<resources>
<declare-styleable name="ChipView">
<attr name="chip_owner" format="enum">
<enum name="p1" value="0"/>
<enum name="p2" value="1"/>
</attr>
</declare-styleable>
</resources>
另外,我有一个 java 枚举来映射它
public enum Player {
P1, P2;
/**
* Returns the opponent of this player
*
* @return the opponent of this player
*/
public Player opponent() {
if (this == P1)
return P2;
else
return P1;
}
}
但是当我将视图添加到相应的布局时,它无法解析枚举值的标签:
<spacebar.backgammoid.ChipView
android:id="@+id/c4"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:chip_owner="p1" /> <!-- Here -->
Android 工作室告诉我: 无法解析符号“p1” 验证 Android XML 文件中的资源引用
我尝试清理和重建我的项目,但没有成功,我还尝试像这样添加资源:
<resources>
<attr name="chip_owner" format="enum">
<enum name="p1" value="0"/>
<enum name="p2" value="1"/>
</attr>
<declare-styleable name="ChipView">
<attr name="chip_owner" />
</declare-styleable>
</resources>
但这都没有达到我的预期。
我做错了吗?我发现了一些关于这个主题的问题,但他们似乎都没有任何问题让 android 解决标签。
编辑
这是作为问题的一部分添加的,因为它不是真正的答案。
当我第一次以编程方式访问枚举时,这个问题自行解决了:
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ChipView);
int player = a.getInt(R.styleable.ChipView_chip_owner, 0);
if (player == 0)
this.setOwner(Board.Player.P1);
else
this.setOwner(Board.Player.P2);
a.recycle();
}
现在,如果我删除此代码,它仍然能够解析 p1,因此后台永久更改了某些内容。
所以,这个问题在制定时毫无意义,但我仍然想知道为什么失败以及通过访问类中的值触发了什么变化(出现的值在我访问属性后立即自动完成)使用
context.obtainStyledAttributes(attrs, R.styleable.ChipView);
所以为了重现这个,你必须:
- 创建视图,添加枚举属性
- 在布局中使用此属性的任何值(应该失败)
- 根据需要多次重建项目(应该仍然失败)
- 从 View 构造函数访问枚举(应该停止失败)
如果这不能重现问题,那么我的问题毫无意义,可以安全删除
顺便说一句,我正在跑步:
- android-studio 1.2.2
- gradle 2.2.1
- oracle JDK 1.8.0_45
- Ubuntu 15.04_amd64
【问题讨论】:
-
你的布局中有
xmlns:app="http://schemas.android.com/apk/res-auto"吗? -
是的,app:chip_owner 也是自动补全建议的,不会导致任何错误
标签: java android xml android-layout enums