2013-03-14 70 views
1

我需要找到出路如何檢索檢查狀態,代碼如下創建複選框:如何檢查複選框是否在Android應用程序中被選中或未選中?

for (int i = 0; i < cnt; i++) { 
        cb = new CheckBox(getApplicationContext()); 
        TextView txt = new TextView(getApplicationContext()); 
        final LinearLayout ll2 = new LinearLayout(
          PollActivity.this); 
        ll2.setOrientation(LinearLayout.HORIZONTAL); 
        ll2.addView(txt); 
        ll2.addView(cb); 
        txt.setText(PersianReshape 
          .reshape(last_poll_array[i][1])); 
        txt.setTypeface(face); 
        ll.setGravity(Gravity.RIGHT); 
        ll2.setGravity(Gravity.RIGHT); 
        ll.addView(ll2); 

       } 
       sc.addView(ll); 

任何指導,將不勝感激。

回答

2

你可以檢查你LL2的孩子是這樣的:

boolean oneChecked = false; 
View v = null; 
for(int i=0; i<ll2.getChildCount(); i++) { 
    v = ll2.getChildAt(i); 
    if (v instanceof CheckBox) { 
     if (((CheckBox) v).isChecked()) { 
      oneChecked = true; 
      break; 
     } 
    } 
} 
if (oneChecked) { 
    // Do whatever you like if one CheckBox is checked 
} 
+0

它不工作 – Fcoder 2013-03-14 08:38:23

+0

你能提供一個解釋,爲什麼它不起作用?有什麼例外嗎?我沒有真正測試代碼,但我很確定它應該工作。 – 2013-03-14 09:24:34

4

我認爲你必須使用一個for循環來檢查一個複選框是否被選中或不喜歡這個

cb.isChecked()==true; 

和對於每個複選框,使用Integer數組保存值爲「true」,「1」爲false。

您可以保存此文件是,SharedPrefrences或CoreData,這樣下一次運行該應用程序,它會保持相同的價值觀

0

此代碼使您能夠存儲複選框的IDS。我開發了Michael Schmidt的代碼。非常感謝,邁克爾!

ArrayList<Integer> check = new ArrayList<Integer>(); 

for(int k=0;k<ll.getChildCount();k++){ 
      View v = ll.getChildAt(k); 
      if(v instanceof CheckBox){ 
       if(((CheckBox)v).isChecked()){ 
        check.add(ll.getChildAt(k).getId()); 
       } 
      } 
     } 
0

試試這個:

if(chckbxcuger.isSelected())rezultatas.setText("cuger"); 
    if(chckbxmilk.isSelected())rezultatas.setText("milk"); 
    if(chckbxCukrus.isSelected()&&chckbxPienas.isSelected())rezultatas.setText("cuger and milk");