本文介绍了DrawableCompat setTint无法在API 19上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DrawableCompat来为drawable着色,如下所示,在API 19上似乎无法使用着色.我正在使用支持库版本23.3.0

I am using the DrawableCompat for tinting drawable as below, tinting doesn't seem to be working on API 19. I am using the support lib version 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);
        }
    }

推荐答案

我遇到了同样的问题.我在 https://stackoverflow.com/a/30928051 中合并了帖子,并尝试了API 17、19、21、22, 23和带有SupportLib 23.4.0的N Preview 3来找到解决方案.

I had the same problem. I combined the posts in https://stackoverflow.com/a/30928051 and tried the APIs 17, 19, 21, 22, 23 and N Preview 3 with SupportLib 23.4.0 to find a solution.

即使提到了,compat类也会对棒棒糖之前的设备使用过滤器(请参见 https://stackoverflow.com/a/27812472/2170109 ),它无法正常工作.

Even if it is mentioned, that the compat-class will use a filter for pre-lollipop-devices (see https://stackoverflow.com/a/27812472/2170109), it's not working.

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

Now, I check the API myself and use the following code, which is working on all tested APIs (for 17 and up).

    // 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);
    }

这篇关于DrawableCompat setTint无法在API 19上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:02