2012-03-09 19 views
7

アクティビティクラスで属性値「必須」を取得するにはどうすればよいですか?Android:アクティビティクラスの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" /> 
のEditTextで

+1

をあなたは答えを見つけるのですか?私は同じ質問で苦労している:) –

答えて

2

コンストラクタデータを読み取るためのロジックを追加from 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(); 
    } 

スイッチ構文は、多くのカスタム属性をチェックするために使用されました。あなたが1つの属性だけに興味があるなら、あなたはより多くを学びたいのであれば、特にXMLを使用する方法ハンドラを追加する方法この読み取り属性switch文

をスキップすることができます。 Long press definition at XML layout, like android:onClick does

関連する問題