拥有这个自定义 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/