9

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

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

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

</resources>

Then in layout I set:

<com.xx.yy.EditTextValidateablePreference
    ...
    ns:errorMessage="@string/validation_email_mail_server_invalid"
    />

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:

context.getResources().getString(messageId)

?

Thanks !

hsz
  • 136,835
  • 55
  • 236
  • 297

2 Answers2

25

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);
ta.recycle();
Community
  • 1
  • 1
Martin Nordholts
  • 10,028
  • 2
  • 37
  • 42
  • Why should you use "Context.obtainStyledAttributes(AttributeSet set, int[] attrs) and TypedArray.getString(int index) instead of AttributeSet.getAttributeValue(...)"? – Lindsay-Needs-Sleep Nov 01 '17 at 02:59
  • It appears that AttributeSet.getAttributeValue will not include themes in determining the result and will not resolve references for you (eg. "@string/my_label"). See [AttributeSet](https://developer.android.com/reference/android/util/AttributeSet.html) – Lindsay-Needs-Sleep Nov 01 '17 at 03:11
12
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...

getResources().getString(resID);
Kumar Bibek
  • 8,851
  • 2
  • 36
  • 64