嗯,我最近开始使用VectorDrawables,我以为它们在所有的安卓版本中都能正常工作,但看起来它们在棒棒糖之前的设备上会崩溃。
事情是这样的,我正在用这个代码创建一个着色的可绘制:
Drawable tintedDrawable = getTintedIcon(
ContextCompat.getDrawable(context, R.drawable.ic_android),
ThemeUtils.darkTheme ? light : dark);
public static Drawable getTintedIcon(Drawable drawable, int color) {
if (drawable != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable) {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
drawable = DrawableCompat.wrap(drawable.mutate());
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN);
DrawableCompat.setTint(drawable, color);
return drawable;
} else {
return null;
}
}创建着色的可绘制文件后,我使用以下命令设置它:imageView.setImageDrawable(tintedDrawable);
这在棒棒糖和更新的安卓版本中可以正常工作,但在较老的版本中则不能。
根据Chris Banes' Medium post的说法,我可以使用以下两种方法之一:app:srcCompat="@drawable/ic_android"
或imageView.setImageResource(R.drawable.ic_android);
但是,当我需要以编程方式对其进行着色时,我该怎么办呢?有人能帮我和/或给我解释一下吗?
提前谢谢。
我已经在我的build.gradle文件中包含了这个,以防万一:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}发布于 2016-06-19 00:44:12
尝试将其声明给ImageView:
app:srcCompat="@drawable/ic_iconname"/>但在此之前,如果您使用的是gradle v2.0 +,请在您的gradle中添加以下内容:
vectorDrawables.useSupportLibrary = true发布于 2016-06-19 02:35:10
如果这会有帮助,请不要这样做,但这是我使用的代码,到目前为止还没有遇到任何问题。
public static boolean isAboveOrEqualAPILvl(int apiLvl) {
return Build.VERSION.SDK_INT >= apiLvl;
}
@TargetApi(Build.VERSION_CODES.M)
public static int getResourceColor(@NonNull Context context, @ColorRes int id) {
if (isAboveOrEqualAPILvl(Build.VERSION_CODES.M)) {
return context.getColor(id);
} else {
//noinspection deprecation
return context.getResources().getColor(id);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Nullable
public static Drawable getIconDrawable(@NonNull Context context, @DrawableRes int drawableId,
int colorId, boolean isMutate) {
Drawable drawable;
if (isAboveOrEqualAPILvl(Build.VERSION_CODES.LOLLIPOP)) {
drawable = context.getDrawable(drawableId);
} else {
//noinspection deprecation
drawable = context.getResources().getDrawable(drawableId);
}
drawable = isMutate ? DrawableCompat.wrap(drawable).mutate() : DrawableCompat.wrap(drawable);
if (colorId>-2) {
DrawableCompat.setTint(drawable, getResourceColor(context, colorId));
}
return drawable;
}
public static void changeDrawableTint(@Nullable Context context, @NonNull Drawable drawable,
@ColorRes int colorId) {
if (context==null) { return; }
DrawableCompat.setTint(drawable, getResourceColor(context, colorId));
}https://stackoverflow.com/questions/37898784
复制相似问题