Hi everyone,
I am a newbie on Android Development. I have a question about the RecyclerView’s swipe :
Is it possible to enable the swipe just ONLY for some items and not for the whole ?
Hi everyone,
I am a newbie on Android Development. I have a question about the RecyclerView’s swipe :
Is it possible to enable the swipe just ONLY for some items and not for the whole ?
Hey @keldii,
Good to hear from you. ![]()
Yes, it is possible to enable the swipe for some items.
I’ve taken the project from the Android RecyclerView tutorial, then updated the setRecyclerViewItemToucherListener method.
private fun setRecyclerViewItemTouchListener() {
val itemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, viewHolder1: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
// If the Viewholder is a PhotoHolder type, swipe it away!
if(viewHolder is RecyclerAdapter.PhotoHolder) {
val position = viewHolder.adapterPosition
photosList.removeAt(position)
recyclerView.adapter!!.notifyItemRemoved(position)
} else {
// We have a different view holder type, don't do anything!
}
}
}
val itemTouchHelper = ItemTouchHelper(itemTouchCallback)
itemTouchHelper.attachToRecyclerView(recyclerView)
}
The ItemTouchHelper.onSwiped method contains a RecyclerView.ViewHolder object as a parameter, you can use the Viewholder to check if it’s an item you would like to be swiped away.
I’ve attached the project for you to try out, I also recommend going through the RecyclerView tutorial above.
Any questions, please let me know.
Darryl
galacticon-check-recyclerview-item.zip (347.5 KB)