1

我有一個自定義的UI組件,它具有另一個自定義UI組件(爲了方便起見分開)。將XML自定義屬性從自定義UI組件傳遞到自定義UI子組件

我希望能夠將我自己的屬性傳遞給父組件,並在子組件內讀取它們。這樣,開發人員唯一需要看到的就是父組件,而不需要知道里面還有另一個組件。

例如,這是應用程序的主要佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:udinic="http://schemas.android.com/apk/res/com.udinic" 
android:id="@+id/main" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"> 

    <com.udinic.FatherComponent android:id="@+id/fatherComp" 
    android:layout_width="fill_parent" 
    udinic:itemNum="9" 
    android:layout_height="wrap_content" /> 

</LinearLayout> 

和父親組件的XML看起來是這樣的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:udinic="http://schemas.android.com/apk/res/com.udinic" 
android:id="@+id/fatherLayout" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"> 

    <com.udinic.SubComponent android:id="@+id/subComp" 
    android:layout_width="fill_parent" 
    udinic:itemNum=<<Get the itemNum passed to me>> 
    android:layout_height="wrap_content" /> 

</LinearLayout> 

我沒有找到任何這種使用做XML僅限於。有誰知道任何可以幫助解決這個問題的東西?

感謝

回答

0

你需要用你的父親類的構造函數的值傳遞到子類。

public FatherClass(Context context, AttributeSet attrs) 
{ 
    super(context, attrs, LAYOUT); 
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomLayout); 
    //for string attribute 
    textView.setText(getStringAttribute(typedArray, R.styleable.CustomLayout_labelText)); 
    //for resources 
    int textAppearance = typedArray.getResourceId(R.styleable.CustomLayout_textAppearance, -1); 
    textView.setTextAppearance(context, textAppearance); 
    //for integers 
    int inputType = typedArray.getInt(R.styleable.CustomLayout_inputType, -1); 
    editText.setInputType(inputType); 
}