gpt4 book ai didi

android - TypedArray 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:56 25 4
gpt4 key购买 nike

我正在学习自定义组件,我在使用自定义 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)。我是否遗漏了什么或者这是正常行为?

最佳答案

好的,我想出了我的问题的答案。答案是我只是使用了没有命名空间的自定义 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>

一切正常。

关于android - TypedArray 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7472461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com