0

所以我遇到了一个奇怪的问题......我制作了一些代码来为Drawable着色,并且它适用于Vector资产的所有Android版本,但不适用于常规PNG资产。代码如下:可绘制的着色代码适用于Vectors,但不适用于PNG

public class TintHelper { 

    private Context mContext; 

    public TintHelper(Context context) { 
     mContext = context; 
    } 

    public Drawable getTintedDrawableFromResource(int resourceID, ColorStateList colorStateList) { 
     Drawable original = AppCompatDrawableManager.get().getDrawable(mContext, resourceID); 
     return performTintOnDrawable(original, colorStateList); 
    } 

    private Drawable performTintOnDrawable(Drawable drawable, ColorStateList colorStateList) { 
     Drawable tinted = DrawableCompat.wrap(drawable); 
     DrawableCompat.setTintList(tinted, colorStateList); 
     return tinted; 
    } 
} 

当我指定一个矢量资源的资源ID,代码完美的作品,按下时图像着色,但是当我使用一个普通PNG,没有应用色调时,图标被按下。如果任何人有任何想法,为什么这不起作用,请发布一种可能支持这两种资产类型的替代方法。

提前致谢!

+0

你正在使用什么版本的'appcompat-v7' /'support-v4'?最新的? 24.2.0? – pskink

+0

@pskink 24.2.1。请参阅下面的答案以获取解决方案。 – privatestaticint

+0

它只适用于24.2.0,我(双)检查,不需要自定义视图 – pskink

回答

0

它适用于我的环境中的PNG。

一套这样的:

int resourceID = R.drawable.ic_launcher; 
TintHelper tintHelper = new TintHelper(this); 
Drawable drawable = tintHelper.getTintedDrawableFromResource(resourceID, 
     ContextCompat.getColorStateList(this, R.color.colors)); 

ImageView imageView = (ImageView) findViewById(R.id.image); 
imageView.setImageDrawable(drawable); 

colors.xml是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_focused="true" android:color="@android:color/holo_red_dark"/> 
    <item android:state_selected="true" android:color="@android:color/holo_red_dark"/> 
    <item android:state_pressed="true" android:color="@android:color/holo_red_dark"/> 
    <item android:color="@android:color/white"/> 
</selector> 
+1

谢谢,但它仍然不适合我。我在我的回答中概述了我的修复。 – privatestaticint

0

我发现这个问题。本质上,DrawableCompat.setTintList()在Android 21及更高版本上无法正常工作。这是由于它们的实现在状态发生变化时不会调用invalidate()。更多细节可以在bug report上阅读。

为了得到这个着色代码对所有平台和所有资源类型的工作,我需要创建一个自定义的ImageView类,如下图所示:

public class StyleableImageView extends AppCompatImageView { 

    public StyleableImageView(Context context) { 
     super(context); 
    } 

    public StyleableImageView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public StyleableImageView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

    // This is the function to override... 
    @Override 
    protected void drawableStateChanged() { 
     super.drawableStateChanged(); 
     invalidate(); // THE IMPORTANT LINE 
    } 
} 

希望这有助于有人不得不应付类似的情况。

相关问题