2012-02-23 165 views
28

當按鈕被點擊時,我需要檢查複選框的值。 Java代碼:Android:獲取選中的複選框值

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); 
+0

你想獲得複選框的值嗎?你的意思是,你想知道複選框的狀態,或者其他什麼?請多說明一下你的要求。 – Hiral 2012-02-23 10:51:49

+0

如果用戶選擇單個,多個複選框需要顯示消息,則需要僅選擇兩個複選框。點擊按鈕後,我需要知道選中的複選框值。 – Kamal 2012-02-23 10:54:41

+0

它仍然不完全清楚。您想阻止用戶選擇多個/少於2個複選框嗎?還有,你認爲checkbox的價值是什麼?它的檢查狀態或其文本? – Hiral 2012-02-23 11:03:37

回答

6

正確的選項得到Checkbox值正在使用的方法:

isChecked()當前檢查的stat視圖

dualcamera1.isChecked() 

isEnable()的e如果這一觀點被啓用,否則爲false剛剛返回True。

26

您可以撥打isChecked()上一個複選框,以獲取其狀態。如果你想計算你可以存儲的選中複選框的數量,然後在ArrayList中循環。

+0

這是對的❤️ – mghhgm 2016-10-13 08:37:08

39

其簡單:

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 

如果選擇可以節省複選框的細節,在如果只是檢查,在for循環。

7

這可能會幫助您:

//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. 
17

如果複選框未在規定的onCreate()方法則必須使用這樣的事情:

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