Android TextView DrawableTint on pre v23 devices

Is there any way we can direct Drawable to a TextView ? DrawableTint only works at API level 23 and above.

I am currently using Vertical Linear Layout to fulfill my requirements.

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

And it seems enter image description here

Android studio offers me to use Compound Drawble with TextView to achieve this. And I can achieve this, but I cannot find a way to Tint drawing.

 <TextView style="@style/ChoiceIllustratorTextStyle" android:drawablePadding="4dp" android:drawableTop="@drawable/ic_account_balance_white_24dp" android:text="@string/ci_text_university" /> 
+9
source share
3 answers

This answer is based on @kris larson's suggestion.

I use the following methods and works great on all devices.

setTintedCompoundDrawable custom method that takes the value of a TextView for which you want to set the composite output ability, the return identifier res, and the res identifier of your color choice.

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

The tint tintDrawable method looks something like this:

 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; } 
+13
source

Software way to do it

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

This works for all API levels.

This is your best option for pre-marshmallow devices.

+17
source

The AndroidX application library supports toning in TextView starting with version 1.1.0-alpha03 [ ref ] .

Add dependencies to the appcompat library

 dependencies { implementation "androidx.appcompat:appcompat:1.1.0" } 

Then draw in TextView can be tinted from XML like this

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:drawableStartCompat="@drawable/ic_plus" app:drawableTint="@color/red" /> 

Do not forget to enable

 xmlns:app="http://schemas.android.com/apk/res-auto" 

and extend your activity with AppCompatActivity .

+2
source

Source: https://habr.com/ru/post/1262632/


All Articles