How to get android default attributes in a custom view

10,839

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);
Share:
10,839
hosseinAmini
Author by

hosseinAmini

Updated on June 05, 2022

Comments

  • hosseinAmini
    hosseinAmini about 2 years

    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?

  • hosseinAmini
    hosseinAmini about 7 years
    I want to use android:text="some text" in xml and retrieve it in my custom view class like custom attributes
  • Dany Pop
    Dany Pop about 7 years
    Please post your custom view class
  • hosseinAmini
    hosseinAmini about 7 years
    I added my custom view class
  • coyer
    coyer almost 5 years
    seems not to work with mixed-case like "android:textColor"?
  • tynn
    tynn almost 5 years
    This should not make a difference. I've never had issues with it.