我有我的自定义 attr.xml
文档,我在其中指定了 declare-styleable
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="EditTextValidateablePreference">
<attr name="errorMessage" format="reference" />
</declare-styleable>
</resources>
然后在布局中我设置:
<com.xx.yy.EditTextValidateablePreference
...
ns:errorMessage="@string/validation_email_mail_server_invalid"
/>
在 EditTextValidateablePreference.class
中,我得到它:
String validatorErrorMessage = attrs.getAttributeValue(PREFERENCE_NS, "errorMessage");
validatorErrorMessage
的值类似于:@2131099700
我怎样才能得到它的整数值来使用它:
context.getResources().getString(messageId)
?
谢谢!
最佳答案
有一个很好的通用答案,我建议您引用: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();
关于android - 如何从具有引用格式类型的 attr 获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7676469/