José Nobre
José Nobre

Reputation: 5027

Check all checboxes in table layout

I have checkboxes that are created dynamically, and I want to press a button a check them all. The button I metioned is located in toolbar and this is the code from it:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {

            case R.id.action_checkall:

                return true;

Then I have a table row inside a table layout and this is the code from the table row where I create the checboxes

final TableRow row = new TableRow(getApplicationContext());
                    row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                            TableLayout.LayoutParams.WRAP_CONTENT));
                    String[] colText={numerochip};
                    String[] colText2={marcaexploracao,marcaauricular,datanascimento};
                    for(final String text:colText) {
                        final CheckBox ch = new CheckBox(this);
                        ch.setTextColor(Color.parseColor("#808080"));
                        ch.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                                TableRow.LayoutParams.WRAP_CONTENT));
                        ch.setGravity(Gravity.CENTER);
                        ch.setTextSize(16);
                        ch.setPadding(5, 5, 5, 5);
                        ch.setText(text);
                        row.addView(ch);

So I want to know, how to check all the cheboxes with a click of a button. Thanks

Upvotes: 0

Views: 528

Answers (2)

Divyesh Patel
Divyesh Patel

Reputation: 2576

List<View> allVIEWS=new ArrayList<>();

Now whenever you create new checkboxes just add it in list:

CheckBox ch = new CheckBox(this);
......
.......
allVIEWS.add(ch);

Now for checking all at once:

    for (int i=0;i<allVIEWS.size();i++){
        if (allVIEWS.get(i) instanceof CheckBox){
            CheckBox chk = (CheckBox) allVIEWS.get(i);
            chk.setChecked(true);
        }

    }

Upvotes: 4

Chetan
Chetan

Reputation: 226

1) Create a List of checkboxes. (List<CheckBox> checkBoxList)

2) Inside your for loop, after creating checkboxes, add those checkboxes to checkBoxList. (checkBoxList.add(ch))

3) When the button is clicked, use below code.

for(CheckBox checkBox : checkBoxList){

       checkBox.setChecked(true);

  } 

Upvotes: 3

Related Questions