我有一个方法,在textview和button上将vectorDrawable设置为DrawableLeft、DrawableRight等,但是我想让它也适用于普通的Drawable。那么,有没有一种方法可以检查drawables的类型,或者应该使用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());
}
}
最佳答案
总结对答案的评论。据我所知,不容易知道drawableres是否指向vectordrawable。如果有人知道怎么做,请写信。但要解决我的问题,可以使用@pskink建议的android.support.v7.content.res.AppCompatResources
。所以现在的方法是:
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());
}