Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show pre checked checkboxes in android

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.

like image 350
Jaimin Shah Avatar asked Dec 14 '11 08:12

Jaimin Shah


People also ask

How do you check the CheckBox is checked or not in android?

So, the method to know if the check box is checked is : (CheckBox) yourCheckBox. isChecked() it returns true if the check box is checked.

Which property is used to select the CheckBox component in Android?

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.

What is the use of CheckBox?

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.


3 Answers

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);
like image 59
Vladimir Avatar answered Oct 07 '22 18:10

Vladimir


Vladimir's answer didn't work for me. Instead use this:

<CheckBox
...
android:state_checked="true" />
like image 43
user3100317 Avatar answered Oct 07 '22 17:10

user3100317


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);
}
like image 37
jennifer Avatar answered Oct 07 '22 16:10

jennifer