获取 styled 属性中使用的可绘制引用的资源 id

Posted

技术标签:

【中文标题】获取 styled 属性中使用的可绘制引用的资源 id【英文标题】:Get the resource id for the drawable reference used in styled attribute 【发布时间】:2013-04-28 18:52:18 【问题描述】:

拥有这个自定义视图MyView 我定义了一些自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="normalColor" format="color"/>
        <attr name="backgroundBase" format="integer"/>
    </declare-styleable>   
</resources>

并在布局 XML 中按如下方式分配它们:

    <com.example.test.MyView
        android:id="@+id/view1"
        android:text="@string/app_name"
        . . .
        app:backgroundBase="@drawable/logo1"
        app:normalColor="@color/blue"/>

起初我以为我可以使用以下方法检索自定义属性backgroundBase

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getInteger(R.styleable.MyView_backgroundBase, R.drawable.blank);

仅当未分配属性并返回默认R.drawable.blank时才有效。 当app:backgroundBase 被赋值时,会抛出一个异常“无法转换为整数类型=0xn”,因为即使自定义属性格式将其声明为整数,它确实引用了Drawable 并且应该被检索如下:

Drawable base = a.getDrawable(R.styleable.MyView_backgroundBase);
if( base == null ) base = BitMapFactory.decodeResource(getResources(), R.drawable.blank);

这很有效。 现在我的问题:我真的不想从 TypedArray 中获取 Drawable,我想要对应于 app:backgroundBase 的整数 id(在上面的示例中它将是 R.drawable.logo1)。我怎样才能得到它?

【问题讨论】:

【参考方案1】:

原来答案就在那里:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getResourceId(R.styleable.MyView_backgroundBase, R.drawable.blank);

【讨论】:

一些对我有帮助的澄清:R.drawable.blank 是默认资源,以防所请求的资源不存在 谢谢,我不知道我可以参考资源 ID。 getResources().getIdentifier() 是 Google 的一大谜团。(他们的文档绝对烂)

以上是关于获取 styled 属性中使用的可绘制引用的资源 id的主要内容,如果未能解决你的问题,请参考以下文章

将可绘制资源图像转换为位图

Error-JavaScript-SCRIPT5007: 无法获取未定义或 null 引用的属性“style”

Android可绘制对象资源之shape和layer-list使用

无法解析属性“src”中的可绘制对象

将图像从 Android 上的可绘制资源保存到 sdcard

Android Button 背景无法识别/使用可绘制对象