着色 ImageView 在 Android 5.0 上不起作用.想法如何使它再次工作? [英] Tinting ImageView not working on Android 5.0. Ideas how to make it work again?

查看:46
本文介绍了着色 ImageView 在 Android 5.0 上不起作用.想法如何使它再次工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我构建的一个应用程序中,我注意到 ImageViews 在运行新的 Android Lollipop 的设备上没有着色.这是过去在旧版本操作系统上正常工作的代码:

In an application I've built I noticed that the ImageViews are not tinted on devices running the new Android Lollipop. This is the code that used to work correctly on older versions of the OS:

<ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="bottom|right"
            android:contentDescription="@string/descr_background_image"
            android:src="@drawable/circle_shape_white_color"
            android:tint="@color/intent_circle_green_grey" />

这是加载到 ImageView 中的可绘制对象:

and this is the drawable that is loaded in the ImageView:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="@color/white" android:endColor="@color/white"
        android:angle="270"/>
</shape>

再一次,这在运行 JellyBean/Kitkat 的设备上正常工作,但色调对运行 Lollipop 的设备没有影响.任何想法如何解决它?这是操作系统中的错误,还是我应该开始对图像进行不同的着色?

Once again, this is working correctly on devices running JellyBean/Kitkat, but the tint has no effect on devices running Lollipop. Any ideas how to fix it? Is it a bug in the OS, or should I start tinting the image differently?

推荐答案

根据@alanv 的评论,这里是对这个 bug 的 hacky 修复.基本思想是扩展 ImageView 并在膨胀后立即应用 ColorFilter:

As per @alanv comment, here goes the hacky fix to this bug. Basic idea is to extend ImageView and apply ColorFilter right after inflation:

public class TintImageView extends ImageView {

    public TintImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView();
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ColorStateList imageTintList = getImageTintList();
            if (imageTintList == null) {
                return;
            }

            setColorFilter(imageTintList.getDefaultColor(), PorterDuff.Mode.SRC_IN);
        }
    }
}

正如你可能猜到的,这个例子有些局限(Drawable设置在inflation tint之后不会被更新,只使用ColorStateList的默认颜色,也许还有什么否则),但如果你有这个想法,你可以把它适应你的用例.

As you might guess, this example is somewhat limited (Drawable set after inflation tint won't be updated, only default color of ColorStateList is used, and maybe something else), but if you got the idea you can fit it to your use-case.

这篇关于着色 ImageView 在 Android 5.0 上不起作用.想法如何使它再次工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆