0.前言

實作 RecyclerView 能將 item 上下拖拉位移 , 左滑右滑刪除

1.準備

一個正常的顯示資料 RecyclerView [Android] Kotlin-RecyclerView

2.Code

private val itemTouchHelper = ItemTouchHelper(object: ItemTouchHelper.Callback(){
        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder): Int {
            val dragFlags  = ItemTouchHelper.UP or ItemTouchHelper.DOWN
            val swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
           return makeMovementFlags(dragFlags,swipeFlags)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            val fromInt = viewHolder.adapterPosition
            val toInt = target.adapterPosition
            mAdapter.moveItem(fromInt,toInt)
            return true
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            val pos = viewHolder.adapterPosition
            mAdapter.removeItem(pos)
        }

    })

mAdapter Function , moveItem and removeItem

Use Collections.swap , change data position

Use notifyItemMoved change data position on View

inner class ItemAdapter : RecyclerView.Adapter<ItemViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
            return ItemViewHolder(layoutInflater.inflate(R.layout.item_row,parent,false))
        }

        override fun getItemCount() = itemDatas.size

        override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
            holder.itemName.text = itemDatas[position]
        }

        fun moveItem(fromInt: Int, toInt: Int) {
            Collections.swap(itemDatas,fromInt,toInt)
            notifyItemMoved(fromInt,toInt)
        }

        fun removeItem(pos: Int) {
            itemDatas.removeAt(pos)
            notifyItemRemoved(pos)
        }


    }
inner class ItemViewHolder(view: View):RecyclerView.ViewHolder(view){
    val itemName: TextView = view.itemname
}

3.Code

https://github.com/encorex32268/blogthing/tree/master/TestItemTouchHelper

4.Result

 

 

 

最後修改日期: 2019-05-06 15:35:06

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料