0

My Checkbox's background is specified via drawable xml and I want to change the color of these items via code. Different control in Android seems to have different ways to set its color.

<Checkbox android:button="@drawable/custom_checkbox" />

In drawable/custom_checkbox.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/checked" />
    <item android:state_checked="false" android:drawable="@drawable/unchecked" />
</selector>

Most answers on SO stop at the solution above. I am able to change the color via the following code but this code will not work in certain API level (e.g. level 17). I would like something that works across the board.

Drawable d = DrawableCompat.wrap(checkbox.getBackground());
DrawableCompat.setTint(d, newColor);
Boon
  • 40,656
  • 60
  • 209
  • 315
  • Possible duplicate of [Android, TabLayout icon color doesn't change when dragging](http://stackoverflow.com/questions/39475790/android-tablayout-icon-color-doesnt-change-when-dragging) – R. Zagórski Sep 21 '16 at 13:49
  • I don't believe it's a duplicate. I am asking about Checkbox, not tab. Solution also has layer-list in its example, which I don't. – Boon Sep 21 '16 at 13:54
  • Yes it is. The accepted answer in this thread shows, how to tint the state drawable on all API levels. – R. Zagórski Sep 21 '16 at 13:55

2 Answers2

0

maybe this helps you.

and i think this: android:buttonTint="@color/mybrown" is a simple way

Community
  • 1
  • 1
Paul
  • 823
  • 1
  • 11
  • 18
  • 1
    This solution won't work for API level 17 (or possibly anything below API level 21). – Boon Sep 21 '16 at 13:53
0

try this:

Drawable d = DrawableCompat.wrap(checkbox.getBackground());
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DrawableCompat.setTint(d, newColor);

    } else {
        d.mutate().setColorFilter(newColor, PorterDuff.Mode.SRC_IN);
    }
mohammadreza khalifeh
  • 1,510
  • 2
  • 18
  • 32