在Android 4上,无法从自定义视图中的TypedArray获取可绘制内容
我已经为我的自定义视图声明了一些自定义属性在Android 4上,无法从自定义视图中的TypedArray获取可绘制内容,android,Android,我已经为我的自定义视图声明了一些自定义属性 <declare-styleable name="MenuItemView"> <attr name="item_icon" format="reference" /> <attr name="item_title_color" format="reference" /> </declare-styleable> 然后我试着把它画出来 public void initView(Conte
<declare-styleable name="MenuItemView">
<attr name="item_icon" format="reference" />
<attr name="item_title_color" format="reference" />
</declare-styleable>
然后我试着把它画出来
public void initView(Context context, TypedArray a) {
inflate(context, R.layout.menu_item, this);
this.title = findViewById(R.id.tvTitle);
this.icon = findViewById(R.id.ivIcon);
try {
title.setTextColor(a.getColor(R.styleable.MenuItemView_item_title_color, getResources().getColor(R.color.midnight_black)));
Drawable iconDrawable = a.getDrawable(context, R.styleable.MenuItemView_item_icon);
...
} finally {
a.recycle();
}
}
在我的手机上,一切正常,但在安卓4上,它只是说
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_profile_circle.xml from drawable resource ID #0x7f08012b
我发现了一个非常棘手的方法来解决这个问题,将属性类型从引用切换到字符串,然后做一些不好的事情
String indentifier = a.getString(R.styleable.MenuItemView_item_icon);
indentifier = indentifier.replace(".xml", "").replace("res/drawable/", "");
int id = context.getResources().getIdentifier(indentifier, "drawable", context.getPackageName());
Drawable iconDrawable = ContextCompat.getDrawable(context, id);
只需为您的视图设置颜色和图标即可
int titleColorId = a.getResourceId(R.styleable.MenuItemView_item_title_color, getResources().getColor(R.color.midnight_black));
int iconId = a.getResourceId(R.styleable.MenuItemView_item_icon, -1);
title.setTextColor(titleColorId);
if (iconId != -1)
icon.setImageResource(iconId);
int titleColorId = a.getResourceId(R.styleable.MenuItemView_item_title_color, getResources().getColor(R.color.midnight_black));
int iconId = a.getResourceId(R.styleable.MenuItemView_item_icon, -1);
title.setTextColor(titleColorId);
if (iconId != -1)
icon.setImageResource(iconId);