Step #3: Adding a Toolbar
Our app bar will be in the form of a Toolbar widget. This is an ordinary widget that you can put in a layout wherever it needs to go. Traditionally, the app bar appears at the top of the activity, so we will place one there.
Open res/layout/activity_main.xml in Android Studio. Right now, this contains our FragmentContainerView. Now, we want to modify the layout to have a Toolbar at the top.
Switch to the “Design” view if you are not already there. In the “Containers” category of the “Palette”, you should find a Toolbar option:
Toolbar
Drag one from the “Palette” over the ConstraintLayout in the “Component Tree” view to add it as a child widget:
Toolbar
Next, we need to set up the anchoring rules for the Toolbar. It looks like it is in the correct position but that is just the default behavior. We really should set up the rules properly. So, grab the circles on the start, top, and end sides of the Toolbar and connect them with the start, top, and end sides of the ConstraintLayout. Leave the bottom alone. And, since the drag-and-drop editor makes this difficult, you could elect to modify the XML instead and add app:layout_constraintStart_toStartOf="parent", app:layout_constraintEnd_toEndOf="parent", and app:layout_constraintTop_toTopOf="parent" to the Toolbar.
Next, click on the nav_host entry in the “Component Tree” to select the FragmentContainerView. You should see it be connected with the bounds of the ConstraintLayout on all four sides. Grab the top anchor and drag it down until it connects with the bottom of the Toolbar:
FragmentContainerView Top Anchored to
Toolbar Bottom
Again, the drag-and-drop editor makes this difficult. If you prefer, switch to the XML and replace app:layout_constraintTop_toTopOf="parent" to app:layout_constraintTop_toBottomOf="@+id/toolbar" on the FragmentContainerView.
Then, select the Toolbar widget, and in the “Attributes” pane:
- Ensure that the ID is set to
toolbar(it should be by default) - Set the
layout_widthtomatch_constraint(a.k.a.,0dp)
Toolbar
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.