【问题标题】:Passing a XML custom attributes from a custom UI component to a custom UI sub-components将 XML 自定义属性从自定义 UI 组件传递到自定义 UI 子组件
【发布时间】:2011-11-12 02:03:27
【问题描述】:

我有一个定制的 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>

我没有找到任何方法来使用 XMLs only。有谁知道可以帮助解决这个问题?

谢谢

【问题讨论】:

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


    【解决方案1】:

    您需要使用父类的构造函数将值传递给子类。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2011-11-28
      相关资源
      最近更新 更多