How to use standard attribute android:text in my custom view?

Seraphim's picture Seraphim's · Aug 2, 2013 · Viewed 19.7k times · Source

I wrote a custom view that extends RelativeLayout. My view has text, so I want to use the standard android:text without the need to specify a <declare-styleable> and without using a custom namespace xmlns:xxx every time I use my custom view.

this is the xml where I use my custom view:

<my.app.StatusBar
    android:id="@+id/statusBar"
    android:text="this is the title"/>

How can I get the attribute value? I think I can get the android:text attribute with

TypedArray a = context.obtainStyledAttributes(attrs,  ???);

but what is ??? in this case (without a styleable in attr.xml)?

Answer

pskink picture pskink · Aug 2, 2013

use this:

public YourView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int[] set = {
        android.R.attr.background, // idx 0
        android.R.attr.text        // idx 1
    };
    TypedArray a = context.obtainStyledAttributes(attrs, set);
    Drawable d = a.getDrawable(0);
    CharSequence t = a.getText(1);
    Log.d(TAG, "attrs " + d + " " + t);
    a.recycle();
}

i hope you got an idea