有了这个自定义视图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
)。我该如何获取?
R.drawable.blank
是默认的资源。 - HaydenKai