Fcoder
Fcoder

Reputation: 9226

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.

Upvotes: 1

Views: 25150

Answers (5)

Marzieh Bahri
Marzieh Bahri

Reputation: 604

Check in the documents:

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

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

Upvotes: 1

Mantas
Mantas

Reputation: 1

Try this:

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

Upvotes: 0

user5159889
user5159889

Reputation: 1

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

Upvotes: 0

Sumit Sharma
Sumit Sharma

Reputation: 1867

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

Upvotes: 4

Michael Schmidt
Michael Schmidt

Reputation: 391

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
}

Upvotes: 2

Related Questions