I am trying to use the new Android Lollipop API setButtonTintList()
to programmatically apply colors to android CheckBox
es.
I have set the following basic ColorStateList
in checkbox_color.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:color="@color/red" />
<item android:state_checked="false"
android:color="@color/green" />
</selector>
On a specific Button
click in my app I inflate a new layout that contains a CheckBox
into my main layout (mLayoutTotalItemRow
) via:
View itemRow = getActivity().getLayoutInflater().inflate(R.layout.row_add_purchase, mLayoutTotalItemRow, false);
After the inflation, I want to apply checkbox_color.xml
to the new CheckBox
via (the reason I want to do this in code rather than xml is that I want to set different colors depending on some variables):
mCheckBoxEnabled.setButtonTintList(mContext.getResources().getColorStateList(R.color.checkbox_color));
Now a strange thing happens, when the CheckBox
is first created, it is red (hence state_checked="true"
. As soon as I uncheck it, it is green (state_chacked="false"
). But when I check it again now, it changes to ticked but it stays green! Hence somehow the internal view state is not changing to "checked".
My checkbox xml:
<CheckBox
android:id="@+id/cb_item_enabled"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/key_line_1_minus_checkbox_margin"
android:layout_marginEnd="@dimen/key_line_2_minus_key_line_1_minus_checkbox"
android:layout_gravity="center_vertical"
android:checked="true"/>
Any ideas what I am doing wrong here?
I have reported the bug to the Android project. Issue 157166
Fix for the next release 5.1
This is fixed in 5.1, which isn't quite released yet.
Status: FutureRelease
EDIT 10.03.2015
Released in 5.1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With