Home > Software design >  How do I add a button to the left side of the toolbar?
How do I add a button to the left side of the toolbar?

Time:11-30

I have two fragments. When I switch from the first fragment to the second, a back arrow is displayed on the toolbar. How to make that there is no void on the home screen instead of the back arrow, but there is another button?

Toolbar:

<androidx.appcompat.widget.Toolbar
    android:id="@ id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:minHeight="64dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

Both screens: 1

CodePudding user response:

I solved the problem by adding my own button.

<ImageButton
    android:id="@ id/button_settings"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?attr/actionBarItemBackground"
    app:srcCompat="@drawable/ic_settings" />

Please note by specifying android:background="?attr/actionBarItemBackground" you can achieve the same clicking effect as a regular toolbar button.

If you want to hide your button on some screens, add the addOnDestinationChangedListener to NavController:

navController.addOnDestinationChangedListener { _, destination, _ ->
    binding.buttonSettings.visibility =
        if (destination.id == R.id.account_add_fragment) View.GONE else View.VISIBLE
}
  • Related