Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 !

like image 264
hsz Avatar asked Oct 06 '11 15:10

hsz


People also ask

What is Attrs XML?

An <attr> element has two xml attributes name and format . name lets you call it something and this is how you end up referring to it in code, e.g., R. attr. my_attribute . The format attribute can have different values depending on the 'type' of attribute you want.

What is Attributeset in Android?

A collection of attributes, as found associated with a tag in an XML document. Often you will not want to use this interface directly, instead passing it to Resources. Theme. obtainStyledAttributes() which will take care of parsing the attributes for you.

What is the name of the file which is used to declare custom attributes?

Create an XML res/values/attrs. xml file to define new attributes alongwith their data type.


2 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);
ta.recycle();
like image 127
Martin Nordholts Avatar answered Nov 14 '22 08:11

Martin Nordholts


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);
like image 43
Kumar Bibek Avatar answered Nov 14 '22 08:11

Kumar Bibek