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

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

拥有这个自定义 View 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)。我怎样才能得到它?

最佳答案

原来答案就在那里:

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

关于android - 获取 styled 属性中使用的可绘制引用的资源 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374653/

相关文章:

android - 精心设计的 Android 应用程序的开源示例?

c# - 在没有 generic.xaml 的情况下创建自定义控件?

c# - 在 DataGridView 列中使用自定义 CheckBoxComboBox

android - 动态需要可绘制资源的整数资源ID

android - 不同 Android 版本的不同 appWidgetProvider

android - Gradle多项目结构

java - 从适配器类到 Activity 的方法调用

android - 自定义 radio 组

ios - iOS 中导航栏下的选项卡

android - 字符串格式转换为 ?通过数据绑定(bind)