How to get android default attributes in a custom view

hosseinAmini picture hosseinAmini · Jun 16, 2017 · Viewed 8.8k times · Source

I have created a simple custom view that contains a RelativeLayout and an EditText:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edt_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</RelativeLayout>

Also I have added some custom attributes in res/values/attrs.xml and I retrieve these attributes in my custom view constructor and everything works ok.

Now, I want to retrieve EditText default attributes in my custom view for example I want to get android:text attribute in my custom view.

My custom view class (simplified):

public class CustomEditText extends RelativeLayout {
    private int panCount;

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,
            R.styleable.CustomEditText, 0, 0);
        try {
            this.panCount = typedArray.getInt(R.styleable.CustomEditText_panCount, 16);
        } finally {
            typedArray.recycle();
        }
    }
}

How can I do that without redeclaring text attribute in res/values/attrs.xml?

Answer

tynn picture tynn · Jun 16, 2017

You can add android:text to your declared syleable. But be sure to not redeclare it.

<declare-styleable name="CustomEditText">
    <attr name="android:text" />
</declare-styleable>

And then get this value from the style like you would with any other of your attributes with the index of R.styleable.CustomEditText_android_text.

CharSequence text = typedArray.getText(R.styleable.CustomEditText_android_text);