I have a tab + ViewPager
layout and in one of these tabs I have a list view. When I replace that list fragment upon the onclick I can still see the old fragment u
Your fragments should be loaded in FrameLayout
like this
And your fragments should be added/loaded in this frameLayout
by this function
private fun switchFragment(
fragment: Fragment,
addToBackstack: Boolean
) {
//check new fragment is alredy loaded currently, then return
val myFragment =
supportFragmentManager.fragments.lastOrNull()//return current visible fragment or null
if (myFragment != null && fragment::class == myFragment::class) {
return
}
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
//transaction.add(R.id.frameLayout, fragment, fragment.javaClass.name)
transaction.replace(
R.id.frameLayout,
fragment,
fragment.javaClass.name
)//using replace will make sure that the previous fragment won't be visible from new fragment
if (addToBackstack) {
transaction.addToBackStack(fragment.javaClass.name)
}
transaction.commit()
}
So initially, your first fragment should be loaded like this,
switchFragment(HomeFragment(), false)
and then other fragments when you select from bottom navigation view or navigation drawer, call this function like this
switchFragment(MyProfileFragment(), true)