46

I need to get checked checkbox values when button clicked. Java Code:

dualcamera1 = (CheckBox)findViewById(R.id.Camera1_DualDisplay);
dualcamera2 = (CheckBox)findViewById(R.id.Camera2_DualDisplay);
dualcamera3 = (CheckBox)findViewById(R.id.Camera3_DualDisplay);
dualcamera4 = (CheckBox)findViewById(R.id.Camera4_DualDisplay);
dualdisplay = (Button)dialog.findViewById(R.id.DisplayDualVideo);
Kamal
  • 1,051
  • 1
  • 11
  • 24
  • you want to get values of checkbox?you mean,you want to know the status of checkbox,or something else? please explain your requirement bit more. – Hiral Vadodaria Feb 23 '12 at 10:51
  • I need to select only two checkbox if the user selects single,more than mutiple checkboxes need to display message. Once the button clicked i need to know the checked checkbox values. – Kamal Feb 23 '12 at 10:54
  • It's still not clear completely.You want to prevent user from selecting more/less then 2 checkboxes? and also,what do you mean by value of checkbox?its checked state or its text? – Hiral Vadodaria Feb 23 '12 at 11:03
  • User should select only two checkboxes. I need to get checked state. – Kamal Feb 23 '12 at 11:06

5 Answers5

61

Its simple:

static int m=0;
dualDisplay.setOnClickListener(new OnCli....{
     onClick()
     {
          if(dualcamera1.isChecked())
              m++; // you can save this as checked somewhere
          if(dualcamera2.isChecked())
              m++; // you can save this as checked somewhere
          if(dualcamera3.isChecked())
              m++; // you can save this as checked somewhere
          if(dualcamera4.isChecked())
              m++; // you can save this as checked somewhere
     }
});
if(m>2 || m<2)
      // show error message
else
      // code here

you can save checkbox's detail if its selected,in if it is checked,in for loop only.

Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
33

You can call isChecked() on a checkbox to get its status. If you want to count the number of checked checkboxes you could store then in an ArrayList and loop through that.

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
Jon
  • 3,174
  • 11
  • 39
  • 57
26

If CheckBox isn't define in onCreate() method then have to use something like this:

boolean isChecked = ((CheckBox) findViewById(R.id.checkBox1)).isChecked()
14

The correct option to get the Checkbox value is using the method:

isChecked() The current checked state of the view

dualcamera1.isChecked() 

isEnable() just return True if this view is enabled, false otherwise.

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
8

This may help you:

//Returns the enabled status for this view. 
dualcamera1.isEnabled()  //return True if this view is enabled, false otherwise. 

//Indicates whether the view is currently in pressed state.
dualcamera1.isPressed() //return True if this view is enabled, false otherwise. 
Mahm00d
  • 3,881
  • 8
  • 44
  • 83