CheckBox in ListView being reset when it leaves the screen

后端 未结 2 1637
-上瘾入骨i
-上瘾入骨i 2021-01-27 06:32

I have followed the tutorial here to create a custom ListView that shows items with category headers. I have modified the list_item_entry.xml to put a

相关标签:
2条回答
  • 2021-01-27 07:17
    class Item{
     boolean isSection;
     String title;
     boolean isOptionChecbox;
    
     //your getter/setter
    
        @Override
        public String toString() {
            return title;
        }
    }
    
    you Adapter:
    public class listAdapter extends ArrayAdapter<Item> {
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Item i = items.get(position);
        if(i.isSection()){
                  convertView = vi.inflate(R.layout.list_item_section, parent, false);
                  convertView.setOnClickListener(null);
                  convertView.setOnLongClickListener(null);
                  convertView.setLongClickable(false);
                  final TextView sectionView = (TextView) convertView.findViewById(R.id.list_item_section_text);
                  sectionView.setText(si.getTitle());
           } else{
                  convertView = vi.inflate(R.layout. list_item_entry, parent, false);
                  final TextView title = (TextView) convertView.findViewById(R.id.list_item_entry_title);
                  if (title != null) title.setText(ei.getTitle());
    
                  CheckBox optionCheckbox = (CheckBox) convertView.findViewById(R.id.option_checkbox);
                  optionCheckbox.setChecked(ei.isOptionCheckbox());
                  optionCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                      @Override
                      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                          item.setOptionCheckbox(b);
                      }
                });
           }      
        return convertView;
     }
    
    }
    
    0 讨论(0)
  • you need to maintain a status array of type boolean in your activity, pass that array into your list adapter and while setting the checkbox check status of that position, also you need to update that status array likewise on click event of checkbox. try this you will get the desired output.

    //While Setting the checkbox in adapter
    
         if(bStatus[position]==false)
            {
                 itemSet.chSelectItem.setChecked(false);
            }else if(bStatus[position]==true)
                {
                  itemSet.chSelectItem.setChecked(true);
                }   
    

    In your main Activity

          //initilize Arraylist in main Activity
            boolean[] bStatus;
            bStatus = new boolean[BeanArray.size()];
            Arrays.fill(bStatus, false);
        MyAdapter adapter = new MyAdapter(this, BeanArray, bStatus);
    listView.setAdapter(adapter);
    
    0 讨论(0)
提交回复
热议问题