【发布时间】:2011-08-30 17:27:52
【问题描述】:
我正在尝试创建一个控件(单击标题时展开和收缩的面板),我在网上找到了一些代码。在构造函数中,我有
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyControl);
...
int headerId = array.getResourceId(R.styleable.MyControl_header, -1);
正在使用以下 XML 在布局文件中创建控件:
<MyControl
android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/drawer"
header="@+id/header" content="@+id/drawerContent"
android:layout_below="@id/contentContainer" android:background="#00FF00">
<TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@id/header"
android:text="This is a header"/>
<TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@id/drawerContent"
android:text="@string/sample_text" />
</MyControl>
问题是,getResourceId() 返回 -1(即,它似乎找不到设置为属性的资源)。
知道为什么吗?
编辑:忘记包含我的 attrs.xml 文件:
<resources>
<declare-styleable name="MyControl">
<attr name="collapsedHeight" format="dimension" />
<attr name="header" format="reference" />
<attr name="content" format="reference" />
<attr name="animationDuration" format="integer" />
</declare-styleable>
编辑 2:不知何故,我没想过要检查其他属性——我添加了一些其他属性。我也在调试器中检查了它们的值,看起来它们也默认了。所以这不是getResourceId 的问题,这与我如何获取一般属性有关。我是 Android 新手,任何人都可以在我的属性处理代码中看到任何内容吗?
【问题讨论】:
-
什么是 MyControl_header?我看到您没有在 XML 的 MyControl 视图中使用它。
-
对不起;忘记添加 attrs.xml 文件了。
-
再一次,我看不到您在布局 xml 中使用该自定义资源的位置。
-
attrs.xml 中的
<declare-styleable>元素定义了 MyControl 控件的属性。在代码中为“header”属性指定标识符的方式是MyControl_header。该符号是在生成 R 类时定义的。 -
是的,伙计,但您并没有告诉 android MyControl_header 与您的 MyControl 视图有关。