6

我正在学习自定义组件,但在自定义 xml 属性方面遇到了一些问题。
我的自定义组件扩展了 LinearLayout,并且在构造函数(public Custom(Context context, AttributeSet attrs))中,我正在扩展 xml 布局(2 个按钮和 1 个 EditText)。
我还在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)。我错过了什么还是这是正常行为?

4

2 回答 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>

一切正常。

于 2011-09-19T14:49:05.897 回答
4

在 Gradle 项目中,使用

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

这对我有用!

于 2016-03-14T10:10:56.457 回答