首页 > 解决方案 > 在自定义视图中从 Android attr 获取字符串值的资源 ID (R.string.name)

问题描述

attrs.xml我的应用程序有一个自定义视图,按条目设置样式:

<resources>
    <declare-styleable name="MyView">
        <attr name="title" format="reference" />
        <attr name="image" format="reference" />
    </declare-styleable>
</resources>

在我的自定义视图中,我需要检索指定为titlein的资源的资源 ID attrs.xml,但我只能检索指定为 的字符串的内容title。到目前为止,我尝试过使用:

attrs.getAttributeResourceValue(R.styleable.MyView_title, 0)

getSourceResourceId(R.styleable.MyView_title, 0)

但在这两种情况下,返回的值都是 default 0

我对其他类型的属性尝试了相同的方法,例如,Drawable ID 可以通过以下方式轻松检索:

getResourceId(R.styleable.MyView_image, 0)

有什么方法可以检查 XML 中提供了什么 R.string 吗?

标签: androidkotlinattrdeclare-styleable

解决方案


推荐阅读