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