ListView Viewholder checkbox state

前端 未结 3 484
无人及你
无人及你 2020-11-29 10:25

I\'ve some problems with my ListView custom adapter (and its newly implemented viewHolder). I have a ListView with a checkbox for each item (nothing new here). The problem i

相关标签:
3条回答
  • 2020-11-29 11:17

    Here's how I made it work:

    First, you need a separate array for your checked state. It has to be the same size as your adapter's getCount().

    Then on your getView, your checkbox's setOnCheckedChangedListener MUST PRECEED your checkbox.setChecked statements.

    example:

    holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        isChecked[position] = isChecked;
      }
    });
    
    holder.checkBox.setChecked(isChecked[position]);
    
    0 讨论(0)
  • 2020-11-29 11:17

    You should set CheckedBox state outside the initialization of ViewHolder, like the following code:

    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    
    viewHolder.checkedBox.setChecked();
    

    BTW: use SparseBooleanArray instead of two list to store CheckedBox state.

    0 讨论(0)
  • 2020-11-29 11:18

    The problem is because of the fact that listview recycles it views

    so in getView() method

         if (convertView == null)
            {
        ........
             }
        else 
            {
                holder = (ViewHolder) convertView.getTag();
    
    
            }
      // Uncheck needed boxes here... You need to implement your logic 
            if( 'position' is checked earlier)
             holder.check.setChecked(true);
            else
            holder.check.setChecked(false);
    

    You need to write the code to manage the state of view if the convert is not null, because it is a already used view which may be having checked check boxes.

    0 讨论(0)
提交回复
热议问题