2011-10-06 54 views
8

我有我指定declare-styleable我的自定義attr.xml文件:如何從參考格式類型的attr獲取字符串?

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

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

</resources> 

然後在佈局我設置:

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

validatorErrorMessage

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

而在EditTextValidateablePreference.class我得到它具有如下值:@2131099700

我怎樣才能得到它的整數值與使用它:

context.getResources().getString(messageId) 

謝謝!

回答

18

還有我建議你參考一個優秀的將軍回答:Declaring a custom android UI element using XML

特別是,你應該使用Context.obtainStyledAttributes(AttributeSet set, int[] attrs)TypedArray.getString(int index),而不是AttributeSet.getAttributeValue(...):

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

爲什麼要使用「Context.obtainStyledAttributes(AttributeSet set,int [] attrs)和TypedArray.getString(int index)而不是AttributeSet.getAttributeValue(...)」? –

+0

似乎AttributeSet.getAttributeValue在確定結果時不會包含主題,並且不會爲您解析引用(例如,「@ string/my_label」)。請參見[AttributeSet](https://developer.android.com/reference/android/util/AttributeSet.html) –

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

從這個整數,你可以得到的字符串說...

 
getResources().getString(resID);