我有一個方法將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