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 
    } 
} 

希望這有助於有人不得不應付類似的情況。

相關問題