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

ilo*_*mbo 27 android custom-controls declare-styleable android-resources

拥有此自定义视图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>
Run Code Online (Sandbox Code Playgroud)

并在布局XML中将它们分配如下:

    <com.example.test.MyView
        android:id="@+id/view1"
        android:text="@string/app_name"
        . . .
        app:backgroundBase="@drawable/logo1"
        app:normalColor="@color/blue"/>
Run Code Online (Sandbox Code Playgroud)

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

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

仅在未分配属性且R.drawable.blank返回默认值时才有效.
app:backgroundBase赋值时抛出异常"无法转换为整数类型= 0xn",因为即使自定义属性格式将其声明为整数,它实际上引用了a Drawable,应该按如下方式检索:

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

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

ilo*_*mbo 45

事实证明答案就在那里:

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

  • 一些可以帮助我的澄清:`R.drawable.blank`是默认资源,以防请求的不存在 (4认同)