Luk*_*rog 6 android xml-attribute typedarray xml-layout
我正在学习自定义组件,我在使用自定义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>
Run Code Online (Sandbox Code Playgroud)
在我膨胀布局后的构造函数中,我正在尝试读取这样的自定义属性:
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();
}
Run Code Online (Sandbox Code Playgroud)
现在我尝试通过将其添加到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>
Run Code Online (Sandbox Code Playgroud)
这不起作用,我只得到默认值(0,1,5).我错过了什么或这是正常的行为?
好的,我想出了我的问题的答案.答案是我只是使用我的自定义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>
Run Code Online (Sandbox Code Playgroud)
一切顺利.
| 归档时间: |
|
| 查看次数: |
3487 次 |
| 最近记录: |