获取用于样式属性的可绘制引用的资源ID

28

有了这个自定义视图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被分配时,会抛出异常 "Cannot convert to integer type=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个回答

49

结果证明,答案就在那里:

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

4
若请求的资源不存在,R.drawable.blank是默认的资源。 - HaydenKai
谢谢,我不知道我可以引用资源ID。getResources().getIdentifier()是Google的伟大之谜之一..(他们的文档绝对糟糕) - angryITguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接