我已经为自定义视图声明了一些自定义属性
<declare-styleable name="MenuItemView">
<attr name="item_icon" format="reference" />
<attr name="item_title_color" format="reference" />
</declare-styleable>
当我创建视图时,我获得了样式化的属性。我已经尝试了context.obtainStyledAttributes和context.getTheme()。obtainStyledAttributes
public MenuItemView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context, context.obtainStyledAttributes(
attrs,
R.styleable.MenuItemView,
0, 0));
}
public MenuItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context, context.obtainStyledAttributes(
attrs,
R.styleable.MenuItemView,
defStyleAttr, 0));
}
然后我尝试获取可绘制对象
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();
}
}
在我的手机上,一切正常,但是在Android 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);
答案 0 :(得分:1)
仅获取颜色和图标并设置您的视图就可以了!
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);