本文主要是介绍Android 使用ItemTouchHelper实现拖拽、左滑删除效果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最终效果
相关代码
val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {/*** 获取滑动响应的方向 包含两个 1.拖动dragFlags 2.侧滑删除swipeFlags* 代表只能向左侧侧滑删除 当前可以是这样ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT*/override fun getMovementFlags(recyclerView: RecyclerView,viewHolder: RecyclerView.ViewHolder): Int {//表示只能向左侧滑删除val swipeFlags = ItemTouchHelper.LEFT//拖动var dragFlags = 0if (rlv.layoutManager is GridLayoutManager) {//如果是GridView样式,四个方向都支持拖动dragFlags = ItemTouchHelper.UP or ItemTouchHelper.LEFT orItemTouchHelper.DOWN or ItemTouchHelper.RIGHT} else {//如果是listView样式,只支持上下,不支持左右dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN}return makeMovementFlags(dragFlags, swipeFlags)}/*** 拖动的时候不断回调此方法*/override fun onMove(recyclerView: RecyclerView,viewHolder: RecyclerView.ViewHolder,target: RecyclerView.ViewHolder): Boolean {//获取原来的位置val fromPosition = viewHolder.adapterPosition//获取目标的值val targetPosition = target.adapterPositionif (fromPosition < targetPosition) {for (i in fromPosition until targetPosition) {Collections.swap(list, i, i + 1)}} else {for (i in fromPosition downTo targetPosition + 1) {Collections.swap(list, i, i - 1)}}rlv.adapter!!.notifyItemMoved(fromPosition, targetPosition)return true}override fun isLongPressDragEnabled(): Boolean {return true}/*** 侧滑删除后回调的方法*/override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {val position = viewHolder.adapterPositionlist.removeAt(position)rlv.adapter!!.notifyItemRemoved(position)}/*** 拖动选择状态改变回调*/override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {//拖动的时候设置背景为灰色viewHolder?.itemView?.setBackgroundColor(Color.GRAY)}}/*** 回到正常状态的时候回调*/override fun clearView(recyclerView: RecyclerView,viewHolder: RecyclerView.ViewHolder) {viewHolder.itemView.setBackgroundColor(0)}})//绑定recyclerviewitemTouchHelper.attachToRecyclerView(rlv)
这篇关于Android 使用ItemTouchHelper实现拖拽、左滑删除效果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!