還記得之前我們對RecycyleView的項目,實現了上下拖曳的實作。
那麼今天來實作左右滑動吧
我們一樣需要三項物件
那麼一樣先宣告一個class 繼承 ItemTouchHelper.Callback
public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {
private ItemTouchHelperAdapter mAdapter;
public ItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean isLongPressDragEnabled() {
return true;
}
@Override
public boolean isItemViewSwipeEnabled() {
return true;
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDissmiss(viewHolder.getAdapterPosition());
}
}
一樣getMovementFlags函式可以指定項目移動的方向
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
指定拖曳方向往上還是往下,使用|符號表示兩者任一都成立
int swipeFlags = ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT;
指定滑動方向往左還是往右,使用|符號表示兩者任一都成立
這邊設定
int swipeFlags = ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT;
這邊要注意的是,isItemViewSwipeEnabled要設定為true
@Override
public boolean isItemViewSwipeEnabled() {
return true;
}
一樣宣告一個interfece 來作為 RecycleView Adapter與ItemTouchHelper.Callback的接口
interface ItemTouchHelperAdapter {
fun onItemMove( fromPosition : Int, toPosition :Int)
fun onItemDissmiss(position: Int)
}
一樣接下來實作RecyclerView.Adapter
open class recycleViewAdapter(val context: Context, val recordList: MutableList<String>
) :
RecyclerView.Adapter<recycleViewAdapter.ViewHolder>()
, ItemTouchHelperAdapter
{
lateinit var mViewHolder : recycleViewAdapter.ViewHolder
override fun onItemDissmiss(position: Int) {
recordList.removeAt(position)
notifyItemRemoved(position)
}
override fun onItemMove(fromPosition: Int, toPosition: Int) {
Collections.swap(recordList,fromPosition,toPosition)
notifyItemMoved(fromPosition,toPosition)
}
...
}
到這邊左右滑動就實作完成了