【发布时间】:2011-11-20 07:25:59
【问题描述】:
我正在学习自定义组件,但我在自定义 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)。我错过了什么还是这是正常行为?
【问题讨论】:
标签: android xml-attribute xml-layout typedarray