How can I restart fragment from activity in a viewpager2.I tried methods like notifyDataSetChanged()
notifyItemChanged(0)
. But didn't work.
ViewPagerAdapter.kt
class ViewPagerAdapter(
fragmentManager : FragmentManager,
var fragments : MutableList<Fragment>,
lifecycle : Lifecycle
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount() : Int {
return fragments.size
}
override fun createFragment(position : Int) : Fragment {
return fragments[position]
}
}
MainActivity.kt
private val tabsArray = arrayOf("Test1", "Test2")
...
fragmentPagerAdapter = ViewPagerAdapter(
supportFragmentManager,
fragments,
lifecycle
)
viewPager.adapter = fragmentPagerAdapter
TabLayoutMediator(tabs, viewPager) {tab, position ->
tab.text = tabsArray[position]
}.attach()
...
CodePudding user response:
You can try the code below. source:link
MainActivity.kt
...
viewPagerAdapter.refreshFragment(1, ForthFragment())
...
FragmentAdapter.kt
...
fun refreshFragment(index: Int, fragment: Fragment) {
fragments[index] = fragment
notifyItemChanged(index)
}
override fun getItemId(position: Int): Long {
return fragments[position].hashCode().toLong()
}
override fun containsItem(itemId: Long): Boolean {
return fragments.find { it.hashCode().toLong() == itemId } != null
}
...