Previous fragment visible under the new fragment

后端 未结 7 1384
心在旅途
心在旅途 2021-02-05 04:10

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

7条回答
  •  不思量自难忘°
    2021-02-05 04:23

    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)
    

提交回复
热议问题