2012-03-09 2 views
7

액티비티 클래스에서 "필수"속성 값을 얻으려면 어떻게해야합니까?안드로이드 : 액티비티 클래스에서 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

당신이 답을 찾을 수 있습니까 : 당신은 하나 개의 속성에만 관심이 있다면 당신이 더 배우고 싶다면 당신은 특히 어떻게 읽을 속성 XML을 사용하는 방법 처리기를 추가, switch 문

를 건너 뛸 수 있습니다? 나는 같은 질문으로 어려움을 겪고있다 :) –

답변

2

생성자 데이터를 판독하기위한 로직을 추가 출신 : xxx :

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

스위치 구문을 사용하여 많은 사용자 지정 특성을 검사했습니다. Long press definition at XML layout, like android:onClick does

관련 문제