2017-01-11 14 views
5

TextViewで使用されていますか? DrawableTintは、APIレベル23以上でのみ動作します。v3.0以前のデバイスでのAndroid TextView DrawableTint

現在、私はVertical Linear Layoutを使用しています。

<LinearLayout style="@style/ChoiceIllustratorIconTextContainerStyle"> 

    <ImageView 
    style="@style/ChoiceIllustratorImageStyle" 
    android:contentDescription="@string/cd_university" 
    android:src="@drawable/ic_account_balance_white_24dp" /> 

    <TextView 
    style="@style/ChoiceIllustratorTextStyle" 
    android:text="@string/ci_text_university" /> 

</LinearLayout> 

そして、それは次のようになり、enter image description here

Androidのスタジオは私がこれを達成するためにTextViewCompound Drawbleを使用することが示唆されます。そして私はそれを達成することができますが、Tintへの道を見つけることができません。

<TextView 
    style="@style/ChoiceIllustratorTextStyle" 
    android:drawablePadding="4dp" 
    android:drawableTop="@drawable/ic_account_balance_white_24dp" 
    android:text="@string/ci_text_university" /> 
+0

この助けることができる:http://stackoverflow.com/questions/29155463/drawable-tinting-for-api-21 – Gudin

+0

は、私はそれをチェックし、私の場合は役に立たない。ありがとう –

答えて

4

この回答は@kris larsonの提案に基づいています。

次の方法を使用していますが、すべてのデバイスで正常に動作しています。

setTintedCompoundDrawableTextViewに、複合ドロアブル、ドロアブルレースID &、および色選択のres IDを設定するカスタムメソッドです。

private void setTintedCompoundDrawable(TextView textView, int drawableRes, int tintRes) { 
    textView.setCompoundDrawablesWithIntrinsicBounds(
      null, // Left 
      Utils.tintDrawable(ContextCompat.getDrawable(getContext(), drawableRes), 
        ContextCompat.getColor(getContext(), tintRes)), // Top 
      null, // Right 
      null); //Bottom 
    // if you need any space between the icon and text. 
    textView.setCompoundDrawablePadding(12); 
} 

色合いtintDrawable方法は、このように書きます:

public static Drawable tintDrawable(Drawable drawable, int tint) { 
    drawable = DrawableCompat.wrap(drawable); 
    DrawableCompat.setTint(drawable, tint); 
    DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_ATOP); 

    return drawable; 
} 
9

これを行うためのプログラム的な方法は、これは、すべてのAPIレベルのために働く

 Drawable[] drawables = textView.getCompoundDrawables(); 
     if (drawables[0] != null) { // left drawable 
      drawables[0].setColorFilter(color, Mode.MULTIPLY); 
     } 

です。

これは、マシュマロ前のデバイスに最適なオプションです。

+3

そして別の画面や異なるビューの状態で別の色を使用する必要がある場合は、setColorFilterを呼び出す前にdrawableを 'mutate()'したいと思っています。 – user3175580

+1

PorterDuff.Mode.MULTIPLYは私のためには機能しません。 代わりに、PorterDuff.Mode.SRC_ATOPが動作します。 PorterDuff.Mode.MULTIPLYはあなたのためにありますか? –

+0

SRC_ATOPはOPが解決したものだったので、それもあなたのために働くのは驚くべきことではありません。正確には覚えていませんが、全白のピクセルでドロアブルを使用していた可能性があるので、MULTIPLYとSRC_ATOPはほとんど同じに見えます。 OPの互換性クラスを使用する方法も、より良い選択肢です。 –

関連する問題