Remove up button from action bar when navigating using BottomNavigationView with Android Navigation UI library

后端 未结 6 772
时光取名叫无心
时光取名叫无心 2021-02-01 04:29

I\'ve created a small app that has three fragments for top-level navigation through a BottomNavigationView. If you launch the app and click on a navigation button on the bottom

6条回答
  •  余生分开走
    2021-02-01 05:17

    I had the same problem and I found a way to get the current fragment with the NavController.addOnNavigatedListener, so I applied the following logic within my Activity and for now it works for me

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        val navHost = supportFragmentManager
                .findFragmentById(R.id.navHostFragment) as NavHostFragment
    
        navHost.navController.addOnNavigatedListener { _, destination ->
            val showButton = showUpButton(destination.id)
            //Here occurs the magic
            supportActionBar?.setDisplayShowHomeEnabled(showButton)
            supportActionBar?.setDisplayHomeAsUpEnabled(showButton)
        }
    }
    
    //Check according to your convenience which fragment id
    //should show or hide the "Up Button"
    private fun showUpButton(id: Int): Boolean {
        return id != R.id.your_home_fragment && id != R.id.your_list_fragment 
                && id != R.id.your_profile_fragment
    }
    

    And this is my project...

    I do not know if it is the best option but if someone has any better suggestion, it will be welcome

提交回复
热议问题