我有一个方法将VectorDrawable设置为TextView和Button上的DrawableLeft,DrawableRight等,但我想使它对普通的Drawable也起作用。那么,有没有办法检查DrawableRes的类型,还是应该使用try/catch? 该方法如下所示:检查DrawableRes是否为VectorDrawable
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());
}
}
所以你想'android.support.v7.content.res.AppCompatResources '? – pskink
它正在工作。谢谢!我刚刚用'AppCompatResources.getDrawable(view.getContext(),left)'替换了'VectorDrawableCompat.create(resources,left,view.getContext()。getTheme())''。 –
还有'android.support.v4.content.res.ResourcesCompat '但我不知道它是否可以正常工作,你可以查看它... – pskink