nAkhmedov
nAkhmedov

Reputation: 3592

Android delete fragment on ViewPager2

I have used ViewPager2 with Fragments as an example here. When i delete first position, fragment is still showing. Do you have any suggestion for this situation.

class PagerAdapter(
    private var activity: FragmentActivity,
    private var itemCount: Int,
    private val conversationId: Long,
    private val currentMediaOffset: Int,
    private val callBack: PhotoViewerActivity.OnPageListener
): FragmentStateAdapter(activity) {
val list = mutableListOf<SwipePhotoViewerFragment>()
override fun createFragment(position: Int): Fragment {
    if (position < list.size) {
        list[position].setCallback(callBack)
        return list[position]
    }

    val fragment = SwipePhotoViewerFragment.create(
            conversationId,
            position,
            currentMediaOffset
    )
    fragment.setCallback(callBack)
    list.add(fragment)

    return fragment
}

override fun getItemCount(): Int {
    return itemCount
}

fun removeItem(position: Int) {
    val fragmentManager = activity.supportFragmentManager
    fragmentManager.beginTransaction().remove(list[position]).commit()
    list.removeAt(position)
    itemCount--
    notifyItemRangeRemoved(position, 1)
    notifyDataSetChanged()
}
}

Upvotes: 2

Views: 1538

Answers (1)

Raptor King
Raptor King

Reputation: 21

when we call notifyDataSetChanged(), android will call method getItemId() in adapter, to check if the item has been updated or not then it returns the position in source code. which basically means in list if you have something like 0-1-2-3-4-5 , if you remove i=2 position , it becomes to 0-1-2-3-4 but the weird thing is i won't change and the data won't update in adapter.

So what you have to do is override getItemId():

val listOfData :MutableList<*> = ArrayList()

override fun getItemId(position: Int): Long 
{
    return lisfOfData[position].hashCode().toLong()
}

this will ensure that each fragment is unique and updated in adapter.

Upvotes: 0

Related Questions