2017-07-08 53 views
2

我正在嘗試在drawable上應用濾鏡,具體取決於用戶在首選項中選定的主要顏色。這是我正在使用的一段代碼。setColorFilter有時不能在android drawable上工作

getResources().getDrawable(R.drawable.ic_batman_1) 
      .setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode.OVERLAY); 

問題是,有時,這段代碼不改變可繪製的濾色器。我已將此代碼放入我的活動(主要活動)onCreate和onResume方法中。

因此,只要應用程序啓動,我希望該濾鏡可應用於該drawable,但有時不會發生。我還注意到這個問題在高端手機(高速處理器,更多RAM)上沒有發生,但只在低端手機上出現。

但是,如果我瀏覽任何其他活動並返回到主要活動,則會應用濾色器。調試代碼和setColorFilter被調用時啓動與適當的顏色參數,但由於某種原因,它沒有得到應用。任何形式的幫助表示讚賞。

請不要低估這個問題,如果你認爲這是一個愚蠢的問題,只是評論,我會把問題放下。我很快就被禁止提問。

回答

1

您試試Drawable.mutate();物業這樣,

Drawable drawable = ContextCompat.getDrawable(context, resource).mutate(); 

drawable.setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode. OVERLAY); 
/** 
* Make this drawable mutable. This operation cannot be reversed. A mutable 
* drawable is guaranteed to not share its state with any other drawable. 
* This is especially useful when you need to modify properties of drawables 
* loaded from resources. By default, all drawables instances loaded from 
* the same resource share a common state; if you modify the state of one 
* instance, all the other instances will receive the same modification. 
* 
* Calling this method on a mutable Drawable will have no effect. 
* 
* @return This drawable. 
* @see ConstantState 
* @see #getConstantState() 
*/ 
public @NonNull Drawable mutate() { 
    return this; 
} 
+0

謝謝Muthukrishnan,它的工作!自上週以來,我一直在爲此撓頭。試圖把這個代碼放在每個可能的位置。你是一個拯救生命的人。 –

相關問題