2016-04-20 40 views
12

我用DrawableCompat詳情如下,着色繪製,着色似乎沒有要在API 19.工作我使用的是支持庫版本23.3.0DrawableCompat setTint不工作的API 19

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

回答

19

我有同樣的問題。我合併了https://stackoverflow.com/a/30928051的帖子,並嘗試了API 17,19,21,22,23和N Preview 3以及SupportLib 23.4.0來尋找解決方案。

即使有人提及,compat-class將使用前棒棒糖設備的篩選器(請參閱https://stackoverflow.com/a/27812472/2170109),它不起作用。

現在,我自己檢查API並使用以下代碼,該代碼正在處理所有測試的API(適用於17歲及以上)。使用程序兼容性支持庫API 15-25

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

最後的東西,對我工作的棒棒糖後不工作。非常感謝您的分享。 – Alin

+1

它對我來說不適用於棒棒糖(API 21)。 我不得不將最低版本更改爲API 22(Build.VERSION_CODES.LOLLIPOP_MR1)。 – Eselfar

+0

結合hardysim和@Eselfar的答案在我的案例中工作。 – LambergaR

7

工程(上24.1.1和上述測試)。

public static Drawable getTintedDrawable(@NonNull final Context context, 
             @DrawableRes int drawableRes, @ColorRes int colorRes) { 
    Drawable d = ContextCompat.getDrawable(context, drawableRes); 
    d = DrawableCompat.wrap(d); 
    DrawableCompat.setTint(d.mutate(), ContextCompat.getColor(context, colorRes)); 
    return d; 
} 
+0

我嘗試過支持庫24.2.1,但不幸的是它不適用於API 19。我轉向了@ hardysim的解決方案。 – Eselfar

+0

它適用於我,我厭倦了API 19 – JFouad

+0

適用於我的API 19/21/25支持庫25.1.1 – mVck

0

基於@localhost答案

Drawable d = DrawableCompat.wrap(ContextCompat.getDrawable(this, R.drawable.ic_rate)); DrawableCompat.setTint(d, Color.parseColor("#AAAAAA")); l.setLogo(d);

我嘗試了API 19> 25,而且運作良好