Fragment re-created on bottom navigation view item selected

后端 未结 15 2584
长发绾君心
长发绾君心 2020-12-07 23:55

Following is my code for bottom navigation view item selected

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationI         


        
15条回答
  •  情深已故
    2020-12-08 00:32

    I've improved @Viven's answers and written it with Kotlin. My version instantiates fragment only for the first time, hides/shows. I'm new at Kotlin so tell me if I can improve anything.

    We need to hold a id to tag map:

    private val fragmentTags = hashMapOf(
            R.id.action_home to "home_fragment",
            R.id.action_profile to "profile_fragment"
    )
    

    The listener code:

    bottomNavigation.run {
        setOnNavigationItemSelectedListener { menuItem ->
            supportFragmentManager.beginTransaction()
                    .let { transaction ->
                        // hide current fragment
                        supportFragmentManager.primaryNavigationFragment?.let {
                            // if selected fragment's tag is same, do nothing.
                            if (it.tag == fragmentTags[menuItem.itemId]) {
                                return@setOnNavigationItemSelectedListener true
                            }
    
                            transaction.hide(it)
                        }
    
                        var fragment  = supportFragmentManager.findFragmentByTag(fragmentTags[menuItem.itemId])
    
                        if (fragment == null) {
                            // instantiate fragment for the first time
                            fragment = when(menuItem.itemId) {
                                R.id.action_home -> HomeFragment()
                                R.id.action_profile -> ProfileFragment()
                                else -> null
                            }?.also {
                                // and add it 
                                transaction.add(R.id.frame, it, fragmentTags[menuItem.itemId])
                            }
                        } else {
                            // if it's found show it 
                            transaction.show(fragment)
                        }
    
    
                        transaction
                                .setPrimaryNavigationFragment(fragment)
                                .setReorderingAllowed(true)
                    }.commitNowAllowingStateLoss()
    
            return@setOnNavigationItemSelectedListener true
        }
    
        //bottomNavigation things
        itemIconTintList = null
        selectedItemId = R.id.action_home
    }
    

提交回复
热议问题