DrawableCompat setTint不适用于API 19

rah*_*lrv 22 android android-support-library android-drawable

我正在使用DrawableCompat来调整drawable,如下所示,着色似乎不适用于API 19.我正在使用支持lib版本23.3.0

Drawable drawable = textView.getCompoundDrawables()[drawablePosition];
if (drawable != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            drawable.setTint(color);
        } else {
            DrawableCompat.setTint(DrawableCompat.wrap(drawable), color);
        }
    }
Run Code Online (Sandbox Code Playgroud)

har*_*sim 28

我有同样的问题.我将这些帖子结合在/sf/answers/2164963601/中,并尝试使用SupportLib 23.4.0的API 17,19,21,22,23和N预览3来查找解决方案.

即使提到这个问题,安装compat级将使用棒棒糖前的设备的过滤器(见/sf/answers/1946873071/),它不工作.

现在,我自己检查API并使用以下代码,该代码适用于所有经过测试的API(适用于17及更高版本).

    // https://stackoverflow.com/a/30928051/2170109
    Drawable drawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.vector));
    image.setImageDrawable(drawable);

    /*
     * need to use the filter | https://stackoverflow.com/a/30880522/2170109
     * (even if compat should use it for pre-API21-devices | https://stackoverflow.com/a/27812472/2170109)
     */
    int color = ContextCompat.getColor(context, R.color.yourcolor);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DrawableCompat.setTint(drawable, color);

    } else {
        drawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
Run Code Online (Sandbox Code Playgroud)

  • 它在Lollipop(API 21)上对我不起作用.我不得不将最低版本更改为API 22(Build.VERSION_CODES.LOLLIPOP_MR1). (2认同)

loc*_*ost 16

使用AppCompat支持库(在24.1.1及更高版本上测试)在API 15-25上运行.

public static Drawable getTintedDrawable(@NonNull final Context context,
                                         @DrawableRes int drawableRes, @ColorRes int colorRes) {
    Drawable d = ContextCompat.getDrawable(context, drawableRes);
    d = DrawableCompat.wrap(d);
    DrawableCompat.setTint(d.mutate(), ContextCompat.getColor(context, colorRes));
    return d;
}
Run Code Online (Sandbox Code Playgroud)


Yai*_*lka 2

我认为在包装好可绘制对象之后,您需要调用mutate()它。请参阅:https ://stackoverflow.com/a/30928051/3032209