Android:如何在Activity类中获取XML的自定义属性

mwr*_*mos 7 xml android

如何在Activity类中获取属性值"required"?

1. values\attrs.xml

<declare-styleable name="EditText"> 
    <attr name="required" format="boolean" />
</declare-styleable> 
Run Code Online (Sandbox Code Playgroud)

2. layout\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" />
Run Code Online (Sandbox Code Playgroud)

Ale*_*lak 2

在 EditText构造函数中添加从 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();
    }
Run Code Online (Sandbox Code Playgroud)

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

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