我正在尝试创建一个控件(在单击标题时扩展和收缩的面板),我在网上找到了一些代码。在构造函数中,我有
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新手,所以任何人都可以在我的属性处理代码中看到任何内容吗?
答案 0 :(得分:2)
想出来。事实证明,属性必须在XML中命名空间;我把
<MyControl
android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/drawer"
header="@+id/header" content="@+id/drawerContent"...
但它必须是
<MyControl xmlns:myPackage="http://schemas.android.com/apk/res/com.my.package"
android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/drawer"
myPackage:header="@+id/header" myPackage:content="@+id/drawerContent"
在我添加之后,它发现值很好。
答案 1 :(得分:0)
您是否在值中添加了资源 - &gt; attrs.xml文件?
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyControl">
<attr name="headerId" format="integer" />
</declare-styleable>
</resources>