【问题标题】:Android: How to get a custom attribute of an XML in Activity classAndroid:如何在 Activity 类中获取 XML 的自定义属性
【发布时间】:2017-08-17 18:27:26
【问题描述】:

如何在我的 Activity 类中获取“必需”属性值?

1.值\attrs.xml

<declare-styleable name="EditText"> 
    <attr name="required" format="boolean" />
</declare-styleable> 

2。布局\text.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:custom="http://schemas.android.com/apk/res/com.mycompany.test"
    android:baselineAligned="false"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/txtTest"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:inputType="text" 
        custom:required="true" />

【问题讨论】:

  • 你找到答案了吗?我正在为同样的问题而苦苦挣扎:)

标签: android xml


【解决方案1】:

在 EditText constructor 中添加从 xml 读取数据的逻辑:

    public EditText(final Context context, final AttributeSet attrs, final int defStyle) 
    {
      super(context, attrs, defStyle);
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditText);

      final int N = a.getIndexCount();
      for (int i = 0; i < N; ++i)
      {
        int attr = a.getIndex(i);
        switch (attr)
        {
            case R.styleable.EditText_required: {
                if (context.isRestricted()) {
                    throw new IllegalStateException("The "+getClass().getCanonicalName()+":required attribute cannot "
                            + "be used within a restricted context");
                }

                boolean defaultValue = false;
                final boolean required = a.getBoolean(attr, defaultValue );
                //DO SOMETHING
                break;
            }
            default: 
                break;
        }
      }
      a.recycle();
    }

switch 构造用于检查许多自定义属性。如果您只对一个属性感兴趣,您可以跳过 switch 语句

如果您想了解更多,尤其是如何使用 xml 属性添加方法处理程序,请阅读以下内容: Long press definition at XML layout, like android:onClick does

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    相关资源
    最近更新 更多