2012-03-09 51 views
7

如何在我的Activity類中獲取屬性值「required」?Android:如何在Activity類中獲取XML的自定義屬性

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" /> 

+1

你找到答案?我正在努力解決同樣的問題:) – 2013-02-09 12:13:04

回答

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(); 
    } 

開關結構被用來檢查許多自定義屬性。如果你只對一個屬性感興趣,你可以跳過switch語句

如果您想了解更多,尤其是如何使用XML屬性讀取此添加方法處理: Long press definition at XML layout, like android:onClick does