2016-04-22 74 views
1

你好我做了一個包含文本視圖(顯示錯誤或建議)這種化合物視圖和編輯文本(輸入)Android自定義複合視圖,如何重新使用屬性?

<TextView 
     android:id="@+id/guidanceOrError" 
     android:gravity="center" 
     android:padding="10dp" 
     android:text="Please input 6 characters and 1 number" 
     android:layout_marginBottom="10dp" 
     android:background="@drawable/input_guidance_background" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <EditText 
     android:id="@+id/inputField" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@drawable/rectangle_border" 
     android:padding="@dimen/login_editText_padding" 
     tools:hint="@string/user_name"/> 

</merge> 

而且這是我在一個活動佈局使用它

<com.ersen.test.widgets.ValidationInputField 
       android:id="@+id/password" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginTop="@dimen/login_editText_top_margin" 
       android:hint="@string/password" 
       android:inputType="textPassword" /> 

我的問題是像hint和inputType屬性被忽略。 這是因爲在我的init(AttributeSet attrs)方法,我沒有得到的屬性了

if(attrs != null){ 
      TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.???); 
      a.recycle(); 
     } 

我的問題是如何使用已經存在的屬性?我不想重新創建它們

請幫助我,感謝閱讀

編輯1 我複合視圖擴展的LinearLayout

回答

1

猜你在談論一個CustomView

但是你應該declare-styleableattrs.xml和使用它像這樣:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="ValidationInputField"> 
     <attr name="android:hint"/> 
     <attr name="android:inputType"/>    
    </declare-styleable> 
</resources> 

所以,編輯您init方法是這樣的:

if(attrs != null){ 
       TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ValidationInputField); 
       String hint = a.getString(R.styleable.ValidationInputField_android_hint); 
       int inputType = a.getInt(R.styleable.ValidationInputField_android_inputType,0); 
       // set these two values in your EditText programmatically 
       EditText editText = (EditText) findViewById(R.id.inputField); 
       editText.setHint(hint); 
       editText.setInputType(inputType); 
       a.recycle(); 
       } 
相關問題