2011-10-06 55 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);