1

我有一个定制的 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的任何方法。有谁知道可以帮助解决这个问题的任何事情?

谢谢

4

1 回答 1

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);
}
于 2013-10-10T20:34:12.553 回答