【发布时间】: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