mercredi 4 mars 2020

Trying to create a method to check if all check boxes are checked then do an action. android

I'm trying to handle an event where if the person checks all the checkboxes an action should happen, which is to make a button clickable. so far i could only check if a box is checked or unchecked but can't find a way to set a counter for how many check boxes clicked. They check boxes are going to be dynamic but in this code sample i just used static values. Tried to set a counter and if i click a check box it should increment but couldn't figure out the right way.

// The method i call

  ArrayList<String> arrayList= new ArrayList<>();
            arrayList.add("2Pac");
            arrayList.add("Biggie");
            arrayList.add("Nas");
            // Create Checkbox Dynamically
            for(int i=0;i<arrayList.size();i++) {

                CheckBox checkBox = new CheckBox(getContext());
                checkBox.setText(arrayList.get(i));
                checkBox.setTextSize(20);
                checkBox.setId(++checkBoxID);
                checkBox.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                   // int counter = -1;
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                    {
                       // String msg = "You have " + (isChecked ? "checked" : "unchecked") + " this box it Checkbox.";
                        //Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                        if(checkBox.isChecked())
                        {
                            //Toast.makeText(getActivity(), ""+ counter, Toast.LENGTH_SHORT).show();
                        }else
                            {
                          //      counter++;
                             //   Toast.makeText(getActivity(), ""+ counter, Toast.LENGTH_SHORT).show();
                            }
                    }
                });

                for(int j=0;j<allCheckBox.size();j++)
                {
                    if(allCheckBox.size()==arrayList.size())
                    {
                        //Toast.makeText(MainActivity.this, ""+ checkBox.getId(), Toast.LENGTH_SHORT).show();
                    }
                }
                // Add Checkbox to LinearLayout
                if (linearLayout != null) {
                    linearLayout.addView(checkBox);
                }

I've spent over a day trying to figure this one so far !! any help or idea is really appreciated.




Aucun commentaire:

Enregistrer un commentaire