Navigation+BottomNavigationView实现的tab效果重建fragment问题

Posted 胖虎

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Navigation+BottomNavigationView实现的tab效果重建fragment问题相关的知识,希望对你有一定的参考价值。

Navigation+BottomNavigationView实现的tab效果重建fragment问题

由于这个控件内部实现会导致fragment频繁重建。因此我们需要对它的listener做一点定制,来处理这个问题


    val periodManagerFragment: Fragment = PeriodManagerFragment()
    val mineFragment: Fragment = MineFragment()

private fun initNavigationView() 
        val navView = uiViewBinding.navView
        navView.setBackgroundColor(resources.getColor(R.color.colorBottomNavigationViewBackgroundColor))
        val navController = findNavController(R.id.nav_host_fragment)
        navView.setupWithNavController(navController)
        var active = periodManagerFragment
        supportFragmentManager.beginTransaction().add(R.id.nav_host_fragment, mineFragment, "2")
            .hide(mineFragment).commit()
        supportFragmentManager.beginTransaction()
            .add(R.id.nav_host_fragment, periodManagerFragment, "1").commit()
        navView.setOnNavigationItemReselectedListener  
        navView.setOnNavigationItemSelectedListener 
            when (it.itemId) 
                R.id.navigation_home -> 
                    supportFragmentManager.beginTransaction().hide(active)
                        .show(periodManagerFragment).commit()
                    active = periodManagerFragment
                
                R.id.navigation_mine -> 
                    supportFragmentManager.beginTransaction().hide(active).show(mineFragment)
                        .commit()
                    active = mineFragment
                
            
            return@setOnNavigationItemSelectedListener true
        
    

以上是关于Navigation+BottomNavigationView实现的tab效果重建fragment问题的主要内容,如果未能解决你的问题,请参考以下文章