简体   繁体   中英

Android delete fragment on ViewPager2

I have used ViewPager2 with Fragments as an examplehere . 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()
}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM