我有一个方法,在TextView和Button上将VectorDrawable设置为DrawableLeft,DrawableRight等,但我想让它也适用于普通的Drawable。那么,有没有办法检查DrawableRes的类型,还是应该使用try / catch? 该方法如下所示:
public static void setViewDrawables(@NonNull View view, @DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) {
final Resources resources = view.getResources();
Drawable vectorDrawableLeft = left != 0 ? VectorDrawableCompat.create(resources, left, view.getContext().getTheme()) : null;
Drawable vectorDrawableTop = top != 0 ? VectorDrawableCompat.create(resources, top, view.getContext().getTheme()) : null;
Drawable vectorDrawableRight = right != 0 ? VectorDrawableCompat.create(resources, right, view.getContext().getTheme()) : null;
Drawable vectorDrawableBottom = bottom != 0 ? VectorDrawableCompat.create(resources, bottom, view.getContext().getTheme()) : null;
if (view instanceof Button) {
((Button) view).setCompoundDrawablesWithIntrinsicBounds(vectorDrawableLeft, vectorDrawableTop, vectorDrawableRight, vectorDrawableBottom);
}
else if (view instanceof TextView) {
((TextView) view).setCompoundDrawablesWithIntrinsicBounds(vectorDrawableLeft, vectorDrawableTop, vectorDrawableRight, vectorDrawableBottom);
} else {
Log.e("ERROR: ViewUtils", "Can't do setCompoundDrawablesWithIntrinsicBounds on " + view.getClass().getName());
}
}
答案 0 :(得分:3)
总结评论的答案。据我所知,没有简单的方法可以知道DrawableRes是否指向VectorDrawable。如果有人知道怎么做,请写信。但是为了解决我的问题,使用android.support.v7.content.res.AppCompatResources
就足够了@pskink建议。所以现在方法看起来像:
public static void setViewDrawables(@NonNull View view, @DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) {
Drawable vectorDrawableLeft = left != 0 ? AppCompatResources.getDrawable(view.getContext(), left) : null;
Drawable vectorDrawableTop = top != 0 ? AppCompatResources.getDrawable(view.getContext(), top) : null;
Drawable vectorDrawableRight = right != 0 ? AppCompatResources.getDrawable(view.getContext(), right) : null;
Drawable vectorDrawableBottom = bottom != 0 ? AppCompatResources.getDrawable(view.getContext(), bottom) : null;
if (view instanceof Button) {
((Button) view).setCompoundDrawablesWithIntrinsicBounds(vectorDrawableLeft, vectorDrawableTop, vectorDrawableRight, vectorDrawableBottom);
} else if (view instanceof TextView) {
((TextView) view).setCompoundDrawablesWithIntrinsicBounds(vectorDrawableLeft, vectorDrawableTop, vectorDrawableRight, vectorDrawableBottom);
} else {
Log.e("ERROR: ViewUtils", "Can't do setCompoundDrawablesWithIntrinsicBounds on " + view.getClass().getName());
}
}
<强>更新强>
在android.support.v7.widget.AppCompatDrawableManager
中有一个方法boolean isVectorDrawable(@NonNull Drawable d)
,它检查Drawable是否为VectorDrawable,但是它将Drawable作为参数,而不是DrawableRes。它看起来像这样:
private static boolean isVectorDrawable(@NonNull Drawable d) {
return d instanceof VectorDrawableCompat
|| PLATFORM_VD_CLAZZ.equals(d.getClass().getName());
}