简体   繁体   中英

Check which checkbox is selected

I got a program that has 50+ checkboxes on one page. And I need to check which boxes are selected.

I know I can do somehting like this:

CheckBox cb1 = (CheckBox) findViewById(R.id.checkBox1);
CheckBox cb2 = (CheckBox) findViewById(R.id.checkBox2);

if (cb1.isChecked){
//get Checkbox name
}
if (cb2.isChecked){
//get Checkbox name
}

But if I have to do this with more then 50 checkboxes, that would take some time. Is their a faster way to check which on is selected? Something like:

int i;

for (i = 0; i<checkBox.length; i++){
  CheckBox cb+i = (CheckBox) findViewById (R.id.checkBox+i);

     if (cb+i.isChecked){
     //get Checkbox name
     }
}

Maybe also good to say: you can select more then 1 checkbox. I hope you know what I mean.

Thanks already, Bigflow

Another workaround may be:

Suppose you have added CheckBox in LinearLayout and you can get the LinearLayout reference in Java and get the child Views like this:

LinearLayout layout= (LinearLayout)findViewById(R.id.checkbox_container);
ArrayList values = new ArrayList();
for(int i=0; i<layout.getChildCount(); i++)
{
    View v = layout.getChildAt(i);
    if(v instanceof CheckBox)
    {
        CheckBox cb = (CheckBox)v;
        if(cb.isChecked())
        values.add(cb.getText().toString());
    }
}

You can make an Array from CheckBox and than add them per code to you layout

CheckBox[] achecker = new CheckBox[50];
achercker[0] = new CheckBox(context);

or with an ArrayList is better when you dont know how much CheckBoxes you will need

ArrayList<CheckBox> lchecker = new ArrayList<CheckBox>(); 
lchecker.add(new CheckBox(context));

set a listener to your checkboxes. checkbox1.setOnCheckChangedListener(this) then override

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if ( isChecked ){
            // to determine which checkbox use buttonView.getId();
        }
}

You can try this one below, set ID by count:

ArrayList<Boolean> booleanList = new ArrayList<Boolean>();

    for(int counter=0; counter<50; counter++) {
        booleanList.add(false);
        CheckBox chkBox = new CheckBox(this);
        chkBox.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1));
        chkBox.setId(counter);
        chkBox.setOnClickListener(chkBoxOnClickListener);
}

private OnClickListener chkBoxOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
        int chkboxID = ((CheckBox)view).getId();
        chkBox = (CheckBox) findViewById(chkboxID);
            if(chkBox.isChecked()) {
                booleanList.set(chkBox, true);
            }

        }
}

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