如何从参考格式类型的attr获取字符串?

hsz*_*hsz 8 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" />
    </declare-styleable>

</resources>
Run Code Online (Sandbox Code Playgroud)

然后在布局我设置:

<com.xx.yy.EditTextValidateablePreference
    ...
    ns:errorMessage="@string/validation_email_mail_server_invalid"
    />
Run Code Online (Sandbox Code Playgroud)

在EditTextValidateablePreference.class我得到它:

    String validatorErrorMessage = attrs.getAttributeValue(PREFERENCE_NS, "errorMessage");
Run Code Online (Sandbox Code Playgroud)

validatorErrorMessage 有一个像这样的值: @2131099700

如何获取其整数值以将其用于:

context.getResources().getString(messageId)
Run Code Online (Sandbox Code Playgroud)

?

谢谢 !

Mar*_*lts 22

有一个很好的一般答案,我建议你参考:使用XML声明自定义android UI元素

特别是,您应该使用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();
Run Code Online (Sandbox Code Playgroud)


Kum*_*bek 11

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

从这个int,你可以通过说...来获取字符串

getResources().getString(resID);