CheckBox will uncheck and check when scrolling down the listview

前端 未结 4 1962
庸人自扰
庸人自扰 2021-01-28 10:21

In my application I use this to count the checked checkbox in real time meaning when tick the box the count above will increase or decrease. but when scrolling down the listview

4条回答
  •  旧时难觅i
    2021-01-28 10:46

    You have to maintain the list of selected checkbox and then set or unset the checkbox based on that list.

    So let's say you have selectedcheckBox list which have the list of the selected checkbox.

    ArrayList<> selectedcheckBox = new ArrayList<>();
    

    So what you can do is:

    lstdept.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                    if (view != null) {
                        selectedcheckBox.add(//Add item to the list)
                        CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_view_item_checkbox);
                        checkBox.setChecked(!checkBox.isChecked());
                        if (!checkBox.isChecked()) {
                            test = test - 1 ;
                        } else {
                            test = test + 1 ;
                        }
                    }
                   getSupportActionBar().setTitle(country + "              Total Count: " + lstdept.getCount()+"       " + test);
                }
    
            });
    

    And when you are populating the listView in your adapter, make a check with selectedcheckBox list. If the value is set in the list then set the checkbox else unset.

    The reason why is this happening because listView recycles itself as it moves out of the view and becomes visible again. So all the values are set again as it becomes visible again. So one should maintain proper checks to inflate the view.

提交回复
热议问题