Fragment re-created on bottom navigation view item selected

后端 未结 15 2565
长发绾君心
长发绾君心 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:51

    Be careful when using replace. Even if providing a fragment that already exists in memory, replace will restart the fragment's lifecycle. To avoid a restart, the transaction object's methods includes add, show, and hide, which can be used to show the correct fragment without restarting it.

    private fun switchFragment(selectedTabIndex: Int) {
        val previousTabIndex = this.currentTabIndex
        this.currentTabIndex = selectedTabIndex
    
        val transaction = supportFragmentManager.beginTransaction()
        val tag = fragments[this.currentTabIndex].tag
    
        // if the fragment has not yet been added to the container, add it first
        if (supportFragmentManager.findFragmentByTag(tag) == null) {
            transaction.add(R.id.container, fragments[this.currentTabIndex], tag)
        }
    
        transaction.hide(fragments[previousTabIndex])
        transaction.show(fragments[this.currentTabIndex])
        transaction.commit()
    }
    

提交回复
热议问题