简体   繁体   中英

How to check if checkbox is checked or unchecked in android application?

I need to find out a way how to retrieve checked state for checkboxes created with code listed below:

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

Any guidance will be appreciated.

I think you have to use a for loop to check whether a checkbox is checked or not like this

cb.isChecked()==true;

and for every checkbox use a Integer array save the value like "0" for true and "1" for false.

You can save this is file, SharedPrefrences or CoreData so that next time you run the application it'll hold the same values

You could check the children of you ll2 like this:

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
}

Check in the documents:

if (checkBox.isChecked()) {
             checkBox.setChecked(false);
         }

check out this link: https://developer.android.com/reference/android/widget/CheckBox.html

This code enables you to store ids of the checkBox. I developed Michael Schmidt's codes. Thanks a lot, Michael!!

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());
                }
            }
        }

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM