我正在学习自定义组件,并且在处理自定义 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)。是我漏掉什么了还是这是正常行为?