Android RecyclerView ItemTouchHelper revert swipe and restore view holder

前端 未结 8 769
栀梦
栀梦 2020-12-04 19:09

Is there a way to revert a swipe action and restore the view holder to its initial position after the swipe is completed and onSwiped is called

8条回答
  •  悲哀的现实
    2020-12-04 19:41

    In the case of using LiveData to provide a list to a ListAdapter, calling notifyItemChanged does not work. However, I found a fugly workaround which involves re-attaching the ItemTouchHelper to the recycler view in onSwiped callback as such

    val recyclerView = someRecyclerViewInYourCode
    
    var itemTouchHelper: ItemTouchHelper? = null
    
    val itemTouchCallback = object : ItemTouchHelper.Callback {
        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction:Int) {
            itemTouchHelper?.attachToRecyclerView(null)
            itemTouchHelper?.attachToRecyclerView(recyclerView)
        }
    }
    
    itemTouchHelper = ItemTouchHelper(itemTouchCallback)
    
    itemTouchHelper.attachToRecyclerView(recyclerView)
    
    

提交回复
热议问题