【问题标题】:Get the resource id for the drawable reference used in styled attribute获取 styled 属性中使用的可绘制引用的资源 id
【发布时间】: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)。我怎样才能得到它?

【问题讨论】:

    标签: android custom-controls android-resources declare-styleable


    【解决方案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 的一大谜团。(他们的文档绝对烂)
    猜你喜欢
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多