Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckBox's isChecked not working when I set initially in java or Kotlin

If I set checkbox state in xml initially, It's working fine but When I set in java or Kotlin dynamically It's not working as I expected.

Like an exmaple when I am setting isChecked = true It supposed to show check box filled with accent color but It's only showing checking border color with accent only but did not filled the color inside.

enter image description here

See when I set the isChecked It's showing accent color in border only.

If I set checkbox state checked = true and set isChecked = false in java It looks like this then

enter image description here

Xml Code of CheckBox

<CheckBox
   android:checked="false"
   android:id="@+id/check_box"
   android:layout_height="wrap_content"
   android:layout_marginTop="@dimen/layout_padding_8dp"
   android:layout_width="wrap_content"
   android:text="@string/check_box_title"/>

Kotlin Code

check_box.isChecked = false // Setting Uncheck
check_box.isChecked = true // Setting Checked
like image 552
Rajan Maurya Avatar asked Jul 10 '18 11:07

Rajan Maurya


People also ask

How to make CheckBox in XML?

To define the click event handler for a checkbox, add the android:onClick attribute to the <CheckBox> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

How do you uncheck a checkbox in Kotlin?

You call c1. isSelected = false , intead use c1. isChecked = false .

How to use checkboxes in android studio?

Typically, you should present each checkbox option in a vertical list. To create each checkbox option, create a CheckBox in your layout. Because a set of checkbox options allows the user to select multiple items, each checkbox is managed separately and you must register a click listener for each one.


1 Answers

I experienced the same with you. I've only tested this in an emulator and one real device, but I found 2 ways to do make it ticked without setting it in xml (for example, you need to fetch something from back-end first to determine whether it has to be ticked from the start or not):

1) Delay command using Handler

Handler().postDelayed({ checkBox?.isChecked = true }, 300)

2) Use toggle() after setting isChecked

checkBox?.isChecked = true 
checkBox?.toggle()

It's as if toggle triggers the UI changes. Problem is, from code above, you'll have your check box ticked, but its isChecked value will be false.

Since I have to set enabled too and somehow it messed up when using toggle(), I settled with the first way. I really hope someone find a more elegant way to solve this...

like image 185
Konayuki Avatar answered Sep 30 '22 06:09

Konayuki