android - 如何从具有引用格式类型的 attr 获取字符串?

标签 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>

然后在布局中我设置:

<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/

相关文章:

java - GitHub 和 Android studio 没有 gradle.build

Eclipse 中的 Android 模拟器速度明显变慢

android - 如何在android中的两个按钮之间画一条线?

Android - 自定义标题栏

Android 圆约束编程半径

Android Lollipop 按钮波纹不显示

android - 创建双行项目布局后无用的属性

android - Circle ProgressBar Android改变厚度等

android - 为什么 `text_size_body` 在 AppCompat 库和 Android Lollipop 中有不同的大小?

android - 4.2中用户结束带有Swipe Action 的应用程序时使用什么事件?