Home » Android » android – How to get a string from attr with reference format type?

android – How to get a string from attr with reference format type?

Posted by: admin June 15, 2020 Leave a comment


I have my custom attr.xml document in which I specified declare-styleable:

<?xml version="1.0" encoding="utf-8"?>

    <declare-styleable name="EditTextValidateablePreference">
        <attr name="errorMessage" format="reference" />


Then in layout I set:


And in EditTextValidateablePreference.class I get it with:

    String validatorErrorMessage = attrs.getAttributeValue(PREFERENCE_NS, "errorMessage");

validatorErrorMessage has a value like: @2131099700

How can I get its integer value to use it with:



Thanks !

How to&Answers:

There’s an excellent general answer which I recommend you to refer to: Declaring a custom android UI element using XML

In particular, you should use Context.obtainStyledAttributes(AttributeSet set, int[] attrs) and TypedArray.getString(int index) instead of AttributeSet.getAttributeValue(…):

TypedArray ta = activityContext.obtainStyledAttributes(attrs, R.styleable.EditTextValidateablePreference);
String theString = ta.getString(R.styleable.EditTextValidateablePreference_errorMessage);


TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.EditTextValidateablePreference);
int resID = array.getResourceId(R.styleable.EditTextValidateablePreference_errorMessage, R.string.default_text);

And from this int, you can get the string by saying…