Android 如何从attr获取引用格式类型的字符串?
我有一个自定义的Android 如何从attr获取引用格式类型的字符串?,android,android-layout,android-xml,Android,Android Layout,Android Xml,我有一个自定义的attr.xml文档,我在其中指定了declare styleable: <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="EditTextValidateablePreference"> <attr name="errorMessage" format="reference" /> </de
attr.xml
文档,我在其中指定了declare styleable
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="EditTextValidateablePreference">
<attr name="errorMessage" format="reference" />
</declare-styleable>
</resources>
validatorErrorMessage
的值类似于:@21301099700
如何获取其整数值以将其用于:
context.getResources().getString(messageId)
?
谢谢 有一个很好的一般性答案,我建议您参考: 特别是,您应该使用and而不是AttributeSet.getAttributeValue(…): TypedArray数组=context.ActainStyledAttributes(attrs,R.styleable.EditTextValidateablePreference); int resID=array.getResourceId(R.styleable.EditTextValidateablePreference\u errorMessage,R.string.default\u text); 从这个int,你可以得到字符串,通过说 getResources().getString(resID); getResources().getString(resID);
为什么要使用“Context.obtainStyledAttributes(AttributeSet,int[]attrs)和TypedArray.getString(int index)而不是AttributeSet.getAttributeValue(…)”?AttributeSet.getAttributeValue在确定结果时似乎不包括主题,也不会为您解析引用(例如“@string/my_label”)。看见
context.getResources().getString(messageId)
TypedArray ta = activityContext.obtainStyledAttributes(attrs, R.styleable.EditTextValidateablePreference);
String theString = ta.getString(R.styleable.EditTextValidateablePreference_errorMessage);
ta.recycle();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.EditTextValidateablePreference);
int resID = array.getResourceId(R.styleable.EditTextValidateablePreference_errorMessage, R.string.default_text);
getResources().getString(resID);