TypedArray不起作用

6

我正在学习自定义组件,并且在处理自定义 XML 属性时遇到了一些问题。
我的自定义组件扩展了 LinearLayout,在构造函数中 (public Custom(Context context, AttributeSet attrs)) 我填充了一个 XML 布局(2 个按钮和 1 个编辑文本)。
我还在 values/attrs 中声明了这些自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="initValue" format="integer" />
        <attr name="stepSize" format="integer" />
        <attr name="maxValue" format="integer"/>
    </declare-styleable>
</resources>

在构造函数中,我填充布局后,尝试像这样读取自定义属性:

   if (attrs != null) {
                TypedArray ta = context.obtainStyledAttributes(attrs,
                        R.styleable.Custom, 0, 0);
                setInitValue(ta.getInt(R.styleable.Custom_initValue, 0));
                setStepSize(ta.getInt(R.styleable.Custom_stepSize, 1));
                setMaxValue(ta.getInt(R.styleable.Custom_maxValue, 5));         
                ta.recycle();
            }

现在我尝试通过将这个自定义组件添加到一个XML布局中来进行测试,方法如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <here.is.my.package.Custom android:id="@+id/add"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        initValue="2" maxValue="7" stepSize="1" />
</LinearLayout>


这不起作用,我只得到了默认值(0、1、5)。是我漏掉什么了还是这是正常行为?

2个回答

8

好的,我找到了我的问题的答案。答案是我简单地使用了没有命名空间的自定义xml属性,而android只是忽略了它们并给了我默认值。在添加了我的命名空间后:

   <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:customAttribute="http://schemas.android.com/apk/res/gere.is.my.package"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <here.is.my.package.Custom android:id="@+id/add"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            customAttribute:initValue="2" customAttribute:maxValue="7" customAttribute:stepSize="1" />
    </LinearLayout>

一切都正常工作。

亲爱的,我也遇到了同样的问题...... 我创建了一个CustomTextView并创建了一个单独的xml布局,这样任何人都可以通过使用<include>来使用它...但是当我尝试获取自定义值属性时...它只提供默认值...有什么建议吗? - CoDe
@Shubh 请发布一个新问题,提供所有问题的细节。 - user
它对我起作用了...在重新启动工作区后进行了项目清理,然后它开始工作了...谢谢。 - CoDe

4
在Gradle项目中,使用

xmlns:customView="http://schemas.android.com/apk/res-auto"

对我很有效!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接