ItemTouchHelper主要是作用在RecyclerView上。本文仍在android 5.0新特性 RecyclerView使用初级基础上。可以看到实现的列表右边的ImageView的样式是一般常见的编辑图片 即提示用户可以进行 列表的移行操作。不知道各位看官是否看个我的这篇文章:自定义View(三) switch开关按钮 ViewDragHelper的使用初级 。其实ViewDragHelper很容易实现表格的滑动删除功能。但其更加普遍适用于所有View。而ItemTouchHelper是Android Design 库中专门针对RecyclerView的移动和滑动操作。好了。看看本文的具体实现。由于布局文件与android 5.0新特性 RecyclerView使用初级本文不在给出。
实现上述功能主要依赖一下辅助类ItemTouchHelperViewHolder、ItemTouchHelperAdapter、OnStartDragListener。(本文主要参考github上开源项目点击打开链接)
1.ItemTouchHelperViewHolder 提供选中和(移行、滑动)手势完成后回调
public interface ItemTouchHelperViewHolder {
/**
* Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped.
* Implementations should update the item view to indicate it's active state.
*/
void onItemSelected();
/**
* Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item
* state should be cleared.
*/
void onItemClear();
}
2 ItemTouchHelperAdapter.java 提供move和dimiss删除接口
public interface ItemTouchHelperAdapter {
/**
* Called when an item has been dragged far enough to trigger a move. This is called every time
* an item is shifted, and <strong>not</strong> at the end of a "drop" event.<br/>
* <br/>
* Implementations should call {@link RecyclerView.Adapter#notifyItemMoved(int, int)} after
* adjusting the underlying data to reflect this move.
*
* @param fromPosition The start position of the moved item.
* @param toPosition Then resolved position of the moved item.
* @return True if the item was moved to the new adapter position.
*
* @see RecyclerView#getAdapterPositionFor(RecyclerView.ViewHolder)
* @see RecyclerView.ViewHolder#getAdapterPosition()
*/
boolean onItemMove(int fromPosition, int toPosition);
/**
* Called when an item has been dismissed by a swipe.<br/>
* <br/>
* Implementations should call {@link RecyclerView.Adapter#notifyItemRemoved(int)} after
* adjusting the underlying data to reflect this removal.
*
* @param position The position of the item