获得风格的属性
问题描述:
有了这个自定义视图MyView
用于绘制参考资源ID我定义了一些自定义属性:获得风格的属性
<?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
)。我怎么才能得到它?
答
事实证明,答案是正确的有:
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'是在情况下,默认的资源请求不存在 – HaydenKai 2016-12-16 09:50:07