I have a problem
How do I show prechecked checkboxes in my android application.
Suppose there are 4 check boxes and I want to show 2 of them checked from the beginning based on a value 0 or 1 assigned to that display variable.
I am a very naive android developer.
So, the method to know if the check box is checked is : (CheckBox) yourCheckBox. isChecked() it returns true if the check box is checked.
When the user selects a checkbox, the CheckBox object receives an on-click event. 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 checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices.
You can either use xml property
<CheckBox
android:id="@+id/cb1"
....
android:checked="true"
/>
or set in your code like
boolean isChecked = ...;
CheckBox cb1 = (CheckBox)findViewById(R.id.cb1);
cb1.setChecked(isChecked);
Vladimir's answer didn't work for me. Instead use this:
<CheckBox
...
android:state_checked="true" />
Just set your value in
checkBox.setTag("zero")
or
checkBox.setTag("one")
and check like this ...
String str = (String) checkBox.getTag();
if(str.equals("zero") || str.equals("one") ){
checkBox.setChecked(true);
}
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