将XML自定义属性从自定义UI组件传递到自定义UI子组件

时间:2011-09-07 11:32:45

标签: android custom-controls android-xml android-custom-attributes

我有一个自定义的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 。有谁知道有什么可以帮助解决这个问题?

由于

1 个答案:

答案 0 :(得分: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);
}