2012-03-09 23 views
7

Làm cách nào để nhận giá trị thuộc tính "bắt buộc" trong Lớp hoạt động của tôi?Android: Cách nhận thuộc tính tùy chỉnh của XML trong lớp Hoạt động

1. giá trị \ attrs.xml

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

2. bố trí \ 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

Bạn có thấy câu trả lời? Tôi đang đấu tranh với cùng một câu hỏi :) –

Trả lời

2

Trong EditText constructor thêm logic để đọc dữ liệu từ 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(); 
    } 

Cấu trúc chuyển đổi được sử dụng để kiểm tra nhiều thuộc tính tùy chỉnh. Nếu bạn chỉ quan tâm đến một thuộc tính bạn có thể bỏ switch tuyên bố

Nếu bạn muốn tìm hiểu thêm, đặc biệt là làm thế nào để thêm điều khiển phương pháp sử dụng xml thuộc tính đọc: Long press definition at XML layout, like android:onClick does

Các vấn đề liên quan