我有一个方法,可以将VectorDrawable设置为TextView和Button的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());
}
}
android.support.v7.content.res.AppCompatResources
? - pskinkAppCompatResources.getDrawable(view.getContext(), left)
替换了VectorDrawableCompat.create(resources, left, view.getContext().getTheme())
。 - Vladimir Jovanovićandroid.support.v4.content.res.ResourcesCompat
,但我不知道它是否也能正常工作,你可以去试试看... - pskink