Android 为什么在使用getAttributeResourceValue时需要指定XML命名空间?
我一直在为一些自定义布局组件使用自定义属性,没有问题。到目前为止,我只使用了简单的属性(string、int等)。在Android 为什么在使用getAttributeResourceValue时需要指定XML命名空间?,android,Android,我一直在为一些自定义布局组件使用自定义属性,没有问题。到目前为止,我只使用了简单的属性(string、int等)。在values/attrs.xml中定义如下: <declare-styleable name="StaticListView"> <attr name="border_size" format="dimension" /> </declare-styleable> 现在,我试图将布局指定为自定义属性,但无法使用上面使用的R.stylea
values/attrs.xml
中定义如下:
<declare-styleable name="StaticListView">
<attr name="border_size" format="dimension" />
</declare-styleable>
现在,我试图将布局指定为自定义属性,但无法使用上面使用的R.styleable
方法
下面是我如何定义属性的:
<declare-styleable name="StaticListView">
<attr name="emptyLayout" format="reference" />
</declare-styleable>
然而,这是可行的:
int emptyLayoutInt = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/de.example.androidapp", "emptyLayout", -1);
我不喜欢硬编码XML名称空间。使用R.styleable
属性可以很好地避免这种情况
我是做错了什么,还是这是错误/预期行为?而不是使用以下行:
int emptyLayoutInt = attrs.getAttributeResourceValue(R.styleable.StaticListView_emptyLayout, -1);
用这个-
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyLayout);
int layoutId = a.getResourceId(R.styleable.MyLayout_text,-1);
返回-1是因为该值在属性集中不可用。我解决了我的问题。我正在浏览
AttributeSet
变量attrs
,因为出于某种原因,但我应该像使用其余属性一样使用TypedArray
实例。下面是一行有效的代码:
int emptyLayoutInt = a.getResourceId(R.styleable.StaticGridView_emptyLayout, -1);
谢谢你的建议。它没有解决我的问题,但它确实让我重新审视了我没有正确使用的
TypedArray
实例。欢迎:)我忘了编写getResourceId。我正在对代码进行最后的修改。
int emptyLayoutInt = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/de.example.androidapp", "emptyLayout", -1);
int emptyLayoutInt = attrs.getAttributeResourceValue(R.styleable.StaticListView_emptyLayout, -1);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyLayout);
int layoutId = a.getResourceId(R.styleable.MyLayout_text,-1);
int emptyLayoutInt = a.getResourceId(R.styleable.StaticGridView_emptyLayout, -1);