Having this custom view MyView
I define some custom attributes:
拥有此自定义视图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>
And assign them as follows in the layout XML:
并在布局XML中按如下方式分配它们:
<com.example.test.MyView
android:id="@+id/view1"
android:text="@string/app_name"
. . .
app:backgroundBase="@drawable/logo1"
app:normalColor="@color/blue"/>
At first I thought I can retrieve the custom attribute backgroundBase
using:
起初我以为我可以使用以下方法检索自定义属性backgroundBase:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getInteger(R.styleable.MyView_backgroundBase, R.drawable.blank);
Which works only when the attribute is not assigned and the default R.drawable.blank
is returned.
When app:backgroundBase
is assigned an exception is thrown "Cannot convert to integer type=0xn" because, even though the custom attribute format declares it as integer, it really references a Drawable
and should be retrieved as follows:
仅在未分配属性且返回默认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);
And this works.
Now my question:
I really don't want to get the Drawable
from the TypedArray, I want the integer id corresponding to app:backgroundBase
(in the example above it would be R.drawable.logo1
). How can I get it?
这很有效。现在我的问题:我真的不想从TypedArray获取Drawable,我想要对应于app:backgroundBase的整数id(在上面的例子中它将是R.drawable.logo1)。我怎么才能得到它?
1 个解决方案
#1
40
It turns out that the answer was right there:
事实证明答案就在那里:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getResourceId(R.styleable.MyView_backgroundBase, R.drawable.blank);
#1
40
It turns out that the answer was right there:
事实证明答案就在那里:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getResourceId(R.styleable.MyView_backgroundBase, R.drawable.blank);