Android 7.0 ListView ChoiceMode选择模式下绘制机理分析 及 ChoiceMode正确使用姿势

工程里原来的代码执行如下操作 在android6.0以下运行良好:

@Override
public void onListItemClick(ListView lv, View view, int position, long id) {
  ....
  position -= mList.getHeaderViewsCount();
        if (mAdapter.isInChoiceMode()) {
            setListItemChecked(position);
            return;
        }
...
}
    public void setListItemChecked(int position) {
        boolean checked = mList.isItemChecked(position);
        mList.setItemChecked(position, checked);
  ...
}

首先以上代码槽点比较多 一会再说。
而工程适配android7.0(24)时发现点击item之后显示的选择状态不更新,Item有被选择上,只不过view没更新。

以上代码第一个槽点:

position -= mList.getHeaderViewsCount();
boolean checked = mList.isItemChecked(position);

mList.isItemChecked(position)的position应该是包含了list的header,所以这里减去Header数量就不对了。

第二个槽点:

  boolean checked = mList.isItemChecked(position);
  mList.setItemChecked(position, checked);

首先这两句的逻辑看似是重复的,根据以前使用ListView选择模式的经验,正常点击操作不用调用setItemChecked(),ListView内部逻辑就会将点击事件处理,进行选择。
读源码,相关逻辑如下:

@Override
public boolean onTouchEvent(MotionEvent ev) {
...
case MotionEvent.ACTION_UP: {    
  onTouchUp(ev);    
  break;
  }
...
}

最终调用到了:AbsListView.performItemClick():

@Override
public boolean performItemClick(View view, int position, long id) {
...
//mCheckedIdStates修改
...
 if (dispatchItemClick) {    
    handled |= super.performItemClick(view, position, id);
    }
   return handled;
 }
 return handled;
}

父类的该方法:
AdaperView.performItemClick():

public boolean performItemClick(View view, int position, long id) {    
  if (mOnItemClickListener != null) {        
    playSoundEffect(SoundEffectConstants.CLICK);        
    mOnItemClickListener.onItemClick(this, view, position, id);        
    if (view != null) {            
      view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);        
      }        
    return true;    
   }    
  return false;
}

所以是先修改了mCheckedIdStates,再调用了mOnItemClickListener的onItemClick方法,所以在 boolean checked = mList.isItemChecked(position)之后调用mList.setItemChecked(position, checked)对保存选取结果无意义。

为何代码在Android 6.0及一下能正常运行,而在7.0以上不行?
首先看6.0和7.0的setItemChecked方法的对比:

android 7.0(24): AbsListView.setItemChecked()

public void setItemChecked(int position, boolean value) {
...
if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL)     {
    itemCheckChanged = oldValue != value;
    // Do not generate a data change while we are in the layout phase or data has not changedif (!mInLayout &&     !mBlockLayoutRequests && itemCheckChanged) {    
     mDataChanged = true;   
     rememberSyncState();            
     requestLayout();
  }
}

android 6.0(23): AbsListView.setItemChecked()

public void setItemChecked(int position, boolean value) {
  // Do not generate a data change while we are in the layout phase
  if (!mInLayout && !mBlockLayoutRequests) {    
    mDataChanged = true;    
    rememberSyncState();    
    requestLayout();
   }
}

以上可见,区别在于6.0时,当点击状态不变时也会调用requestLayout(),而7.0开始只有item的选择状态发生改变时才会调用requestLayout()进行重绘。

 boolean checked = mList.isItemChecked(position);
        mList.setItemChecked(position, checked);

这两句不会改变item的选择状态,所以在7.0后就不会使List重绘了。

那么使用ListView的ChoiceMode的正确姿势是什么呢?
看两段相关代码
AbsListView.updateOnScreenCheckedViews()

/** * Perform a quick, in-place update of the checked or activated state * on all visible item views. This should only be called when a valid * choice mode is active. */
private void updateOnScreenCheckedViews() {    
  final int firstPos = mFirstPosition;    
  final int count = getChildCount();    
  final boolean useActivated = getContext().getApplicationInfo().targetSdkVersion            >= android.os.Build.VERSION_CODES.HONEYCOMB;    
  for (int i = 0; i < count; i++) {        
    final View child = getChildAt(i);        
    final int position = firstPos + i;        
    if (child instanceof Checkable) {            
      ((Checkable) child).setChecked(mCheckStates.get(position));        
     } 
     else if (useActivated) {            
      child.setActivated(mCheckStates.get(position));        
     }    
    }
}

该方法在performItemClick()里被调用。
ListView.setupChild()

private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,        boolean selected, boolean recycled) {
  if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {    
    if (child instanceof Checkable) {        
      ((Checkable) child).setChecked(mCheckStates.get(position));    
    } else if (getContext().getApplicationInfo().targetSdkVersion            
            >= android.os.Build.VERSION_CODES.HONEYCOMB) {             child.setActivated(mCheckStates.get(position));    
   }
}

setupChild()在其item绘制时候会被调用。

所以,让ItemView实现Checkable接口,在Item被选择后就会调用该接口的setChecked方法。
改造后的ItemView大致如此:

public abstract class ItemView extends LinearLayout implements Checkable{
  ...
  public CheckBox mCheckBox;
  private boolean isChecked;
  @Override
  public void setChecked(boolean isItemChecked) {    
    this.isChecked = checked;
    mCheckBox.setChecked(isItemChecked);
  }
  @Override
  public boolean isChecked() {    
    return isChecked;
  }
  @Override
  public void toggle() {    
    setChecked(!isChecked);
  }
}

checkbox不能再响应它自身的点击事件了: 清除焦点并设为不可点击

<CheckBox    
  android:id="@android:id/checkbox"    
  android:layout_width="wrap_content"    
  android:layout_height="match_parent"    
  android:focusable="false"    
  android:clickable="false" />

此外,另一种实现ChoiceMode的方法是在OnItemClick()里和getView()里,根据 mList.isItemChecked(position)来设置checkbox 。但这种方法并不推荐,因为这是在点击和绘制时单独处理checkbox的逻辑。
另外一种是在OnItemClick里直接notifyDataChange()重绘,getView()里根据 mList.isItemChecked(position)来设置checkbox。而这种方法又重新绘制了ListView,开销更大。
还是让ItemView实现checkable接口比较好,绘制次数更少,逻辑更清晰。

    原文作者:qintong000
    原文地址: https://www.jianshu.com/p/53733b379750
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞