【问题标题】:TypedArray not workingTypedArray 不工作
【发布时间】: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


    【解决方案1】:

    在 Gradle 项目中,使用

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

    这对我有用!

    【讨论】:

      【解决方案2】:

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

      一切正常。

      【讨论】:

      • 亲爱的同样的显示问题...我创建了一个 CustomTextView 并创建了一个单独的 xml 布局,所以任何人都可以通过使用 来使用它...但是当我尝试获取自定义value 属性..它只给出默认值...任何建议。
      • @Shubh 请发布一个新问题,提供问题的所有详细信息。
      • 它为我工作....在重新启动工作区后再次进行项目清理..它开始工作...谢谢
      猜你喜欢
      • 2015-09-05
      • 2017-01-01
      • 1970-01-01
      • 2016-06-04
      • 2014-09-11
      • 2018-03-10
      • 2016-10-04
      • 2016-01-24
      • 1970-01-01
      相关资源
      最近更新 更多