Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView tint on AppCompat

I made a few checkboxes and radio buttons with textviews, but they don't get tinted pre-Lollipop.

My textviews extend AppCompatCheckedTextView, are styled as:

<style name="CheckBoxStyle" parent="android:Widget.TextView">
    <item name="android:textAppearance">?android:attr/textAppearance</item>
    <item name="android:drawableRight">?android:attr/listChoiceIndicatorMultiple</item>
    <item name="android:drawableEnd">?android:attr/listChoiceIndicatorMultiple</item>
    <item name="android:clickable">true</item>
    <item name="android:background">?attr/selectableItemBackground</item>
    <item name="android:gravity">center_vertical</item>
    <item name="android:paddingTop">8dp</item>
    <item name="android:paddingBottom">8dp</item>
</style>

and I have my accent defined in my theme:

<style name="AppTheme.Platform.NoActionBar" parent="Theme.AppCompat.NoActionBar">
    <item name="android:selectableItemBackground">@drawable/press_overlay_dark</item>
    <item name="android:borderlessButtonStyle">@style/BorderlessButton</item>

    <item name="android:colorAccent">@color/color_accent</item>
    <item name="colorAccent">@color/color_accent</item>
</style>

I'm building against v21, with a minimum of v16 and using AppCompat v7-22.1.1. My activities extend AppCompatActivity

Genymotion 4.1.1Nexus 5 5.1.1

like image 350
DariusL Avatar asked Jun 05 '15 16:06

DariusL


1 Answers

For Api level 23 >= android:drawableTint="@color/colorPrimary"

For Api level < Api level 23 :

JAVA

private void setTextViewDrawableColor(@RecentlyNonNull TextView textView,@ColorRes int color) {
        for (Drawable drawable : textView.getCompoundDrawables()) {
            if (drawable != null) {
                drawable.setColorFilter(new PorterDuffColorFilter(getColor(color), PorterDuff.Mode.SRC_IN));
            }
        }
    }

USE: setTextViewDrawableColor(txtMyDemoText,R.color.colorPrimary)


Kotlin Extension Function

  fun TextView.setDrawableColor(@ColorRes color: Int) {
          compoundDrawables.filterNotNull().forEach {
              it.colorFilter = PorterDuffColorFilter(getColor(context, color), PorterDuff.Mode.SRC_IN)
        }
   }

USE : txtMyDemoText.setDrawableColor(R.color.colorPrimary)

like image 62
Dipali Shah Avatar answered Sep 22 '22 22:09

Dipali Shah