I am updating my code from using androidx.viewpager
to androidx.viewpager2
. I am paging through an undetermined number of fragments showing data records retrieved from a database. Loading the view pager and paging through my data works nicely but I'm having some trouble with deleting an item and updating the pager adapter. I want to delete an item at any given position by calling the removeItem()
method (see code below) on my adapter. That should remove the item from my database as well as my fragment and then update the view.
Result is that the correct item is removed from the database. But it does not remove the intended fragment from my view pager but the next page instead. The current page remains visible. I have a bit offsetting the position by plus or minus 1 with no success - in contrary: in those cases my delete routine performed as initially expected. I also tried similar considerations as given e.g. here.
I'd like to achieve the following behavior:
- When deleting any item, the page should be removed and the next one in the list displayed.
- When deleting the last/rightmost item in the list, the page should be removed and the previous (now last) page shown.
- When deleting the last remaining item (none left) the activity should finish.
My adapter code:
internal class ShapePagerAdapter(private val activity: AppCompatActivity) : FragmentStateAdapter(activity) {
private val dbManager: DatabaseManager
private var shapeIds: MutableList<String>? = null
init {
dbManager = DatabaseManager(activity)
try {
shapeIds = dbManager.getShapeIds()
} catch (e: DatabaseAccessException) {
// ...
}
}
override fun getItemCount(): Int {
return if (null != shapeIds) shapeIds!!.size else 0
}
override fun createFragment(position: Int): Fragment {
return ShapeFragment.newInstance(shapeIds!![position])
}
fun removeItem(activity: AppCompatActivity, position: Int) {
try {
// Remove from Database.
dbManager.deleteShape(shapeIds!![position])
// Remove from View Pager.
shapeIds!!.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position , itemCount)
// Close if nothing to show anymore.
if (itemCount == 0) {
activity.finish()
}
} catch (e: DatabaseAccessException) {
// ...
}
}
}