How to remove back arrow from action bar in the home fragment when I'm using bottom navigation view

Viewed 825

I've created three fragement and toolbar for every fragment with label. I have used navigate up to switch between home fragment and other fragment. My problem is, in the main fragment i want to remove back arrow from the toolbar. I have tried this actionBar?.setDisplayHomeAsUpEnabled(false) on main activity but it didn't work.Please help me

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val bottomNavView = bottom_nav
    val navController = findNavController(R.id.fragment_nav_host)

    setSupportActionBar(toolbar)
    val actionBar = supportActionBar

    val appbarConfig = AppBarConfiguration(setOf(R.layout.fragment_home,R.layout.fragment_favorite,R.layout.fragment_profile))

    setupActionBarWithNavController(navController,appbarConfig)

    bottomNavView.setupWithNavController(navController)
}

override fun onSupportNavigateUp(): Boolean {
    val navController = this.findNavController(R.id.fragment_nav_host)
    return navController.navigateUp()
}

}

Here is toolbar code on activity_main layout

<androidx.appcompat.widget.Toolbar
     android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:theme="@style/toolbarTheme"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary" />

Screenshoot

3 Answers

You need to disable homebutton for actionbar as below

   setSupportActionBar(toolbar)
   val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar?.setDisplayShowHomeEnabled(false);
            actionBar?.setHomeButtonEnabled(false);
        }

On View Created, add this

(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(false)

Finally found the answer. If you check the documentation of the setupActionBarWithNavController, you will notice that the action bar set up here is returned with the method getSupportActionBar() and NOT getActionBar(), that in every thread is suggested to use.

Now if you want to have this on the fragment level as I wanted, then you also need to cast the activity that the fragment holds to AppCompatActivity, so that you can have access to the supportActionBar.

Like this:

(requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(false)
Related