不多說 先上圖
RecycleView的項目,如果要作到左右滑動以及上下移動位置
可以透過ItemTouchHelper的ItemTouchHelper.Callback來實作。
今天先來講上下拖曳的部分。
先宣告一個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.ACTION_STATE_IDLE;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean isLongPressDragEnabled() {
return true;
}
@Override
public boolean isItemViewSwipeEnabled() {
return false;
}
@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) {
}
}
其中getMovementFlags函式可以指定項目移動的方向
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
指定拖曳方向往上還是往下,使用|符號表示兩者任一都成立
int swipeFlags = ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT;
指定滑動方向往左還是往右,使用|符號表示兩者任一都成立
這邊設定
int swipeFlags = ItemTouchHelper.ACTION_STATE_IDLE;
onMove函式可以處理上下拖曳時的動作
onSwiped函式可以處理左右滑動時的動作
之後宣告一個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)
}
...
}
由於我們在adapter引入了interface ItemTouchHelperAdapter,
所以要override ItemTouchHelperAdapter的兩個方法
onItemDissmiss: 處理滑動時adapter動作
onItemMove: 處理拖曳時adapter動作
之後在activity中,將ItemTouchHelperCallback、ItemTouchHelper與adapter綁定
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
...
var adapter = recycleViewAdapter(this,mlist)
rv_this.adapter =adapter
val layoutManager = LinearLayoutManager(this!!)
rv_this.layoutManager = layoutManager
val callback = ItemTouchHelperCallback(adapter)
val touchHelper = ItemTouchHelper(callback)
touchHelper.attachToRecyclerView(rv_this)
}
}
宣告callback變數將adaptert傳入ItemTouchHelperCallback,並交由touchHelper綁定MainActivity的RecycleView元件
到這邊就可以上下拖曳的實作就完成了