开发者

Accessing the the attributes of the inner Views of a custom layout

开发者 https://www.devze.com 2023-03-26 09:56 出处:网络
I created a custom layout cont开发者_JAVA技巧aining a TextView and a Spinner that extends LinearLayout(called LabeledSpinner).

I created a custom layout cont开发者_JAVA技巧aining a TextView and a Spinner that extends LinearLayout(called LabeledSpinner). I put several of these LabeledSpinners into my main RelativeLayout and obviously I want to set different text for each of their textviews but I don't know how to do it in the xml file.

I need to access the attributes of the inner Views somehow please help. I tried to use [package name].LabeledSpinner.label:text but it didn't work

(label is the id of the textview)


Make LabeledSpinner a styleable (res/values/attrs.xml)

<declare-styleable name="LabeledSpinner">
    <attr name="text" format="string"/>
</declare-styleable>

In your LabeledSpinner

public LabeledSpinner(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LabeledSpinner);
    String text = a.getString(R.styleable.LabeledSpinner_text);
    a.recycle();
}

Note that the text attribute in LabeledSpinner is to be used as LabeledSpinner_text.

Now in your layouts

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourpackage="http://schemas.android.com/apk/res/com.package">
    <com.package.LabeledSpinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        yourpackage:text="This is where your text goes"/>
</LinearLayout>

That should do!

0

精彩评论

暂无评论...
验证码 换一张
取 消