简体   繁体   中英

Check all checkboxes in a listview when one is clicked

I have a listview whereby each listview item has a checkbox that the user can select an item with. I also have a checkbox above the listview which is expected to automatically check all the checkboxes in my list when clicked. I am having problems implementing the appropriate for this. Any ideas?

public class NotesActivity extends AppCompatActivity {
    private CheckBox universalCheckBox;
    private ListView mListNotes;
    NoteListAdapter na;
    private boolean isAnyItemChecked = false;
   private CheckBox mCheckBox;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        mListNotes = findViewById(R.id.main_listview);
        // handling long click for list view item
         mListNotes.setLongClickable(true);
        mListNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                for (int index = 0; index < parent.getChildCount(); ++index) {
                    View nextChild = (parent.getChildAt(index));
                     mCheckBox = nextChild.findViewById(R.id.checkbox);
                    mCheckBox.setVisibility(View.VISIBLE);
                    universalCheckBox.setVisibility(View.VISIBLE);
                }
                CheckBox checkBox = view.findViewById(R.id.checkbox);
                checkBox.setChecked(true);
                isAnyItemChecked = true;
                return true;
            }
        });
        universalCheckBoxLogic();
    }

    private void universalCheckBoxLogic() {
        universalCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             mCheckBox.setChecked(true); // this not working for me

            }
        });
    }
}
universalCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {         
                        checkAll(isChecked);

       }
   }
);   

     private void checkAll(boolean checked){
               for (int index = 0; index < parent.getChildCount(); ++index) {
                    View nextChild = (listView.getChildAt(index));
                     mCheckBox = nextChild.findViewById(R.id.checkbox);
                    mCheckBox.setVisibility(View.VISIBLE);
                    mCheckBox.setChecked(checked);
                }

    }

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