The Android AppBar and CollapsingToolbar Layouts

In this chapter, we will explore how the app bar within an activity layout can be customized and made to react to the scrolling events occurring within other screen views. Using the CoordinatorLayout in conjunction with the AppBarLayout and CollapsingToolbarLayout containers, the app bar can be configured to display an image and to animate in and out of view. For example, an upward scrolling motion on a list can be configured so that the app bar recedes from view and reappears when a downward scrolling motion is performed.

Beginning with an overview of the elements that can comprise an app bar, this chapter will work through various examples of app bar configuration.

The Anatomy of an AppBar

The app bar is the area that appears at the top of the display when an app is running and can be configured to contain various items, including the status bar, toolbar, tab bar, and a flexible space area. Figure 56-1, for example, shows an app bar containing a status bar, toolbar, and tab bar:

Figure 56-1

A blank background color can fill the flexible space area, or as shown in Figure 56-2, an image displayed on an ImageView object:

Figure 56-2

As will be demonstrated in the remainder of this chapter, if the main content area of the activity user interface layout contains scrollable content, the elements of the app bar can be configured to expand and contract as the content on the screen is scrolled.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

The Example Project

For this example, changes will be made to the CardDemo project created in the earlier chapter entitled An Android Studio RecyclerView Tutorial. Begin by launching Android Studio and loading this project.

Once the project has loaded, run the app and note when scrolling the list upwards that the toolbar remains visible, as shown in Figure 56-3:

Figure 56-3

The first step is to make configuration changes so the toolbar contracts during an upward scrolling motion and then expands on a downward scroll.

Coordinating the RecyclerView and Toolbar

Load the activity_main.xml file into the Layout Editor tool, switch to Code mode, and review the XML layout design, the hierarchy of which is represented by the diagram in Figure 56-4:

Figure 56-4

At the top level of the hierarchy is the CoordinatorLayout, which, as the name suggests, coordinates the interactions between the various child view elements it contains. As highlighted in An Android Floating Action Button and Snackbar Tutorial for example, the CoordinatorLayout automatically slides the floating action button upwards to accommodate the appearance of a Snackbar when it appears, then moves the button back down after the bar is dismissed.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

The CoordinatorLayout can similarly be used to cause elements of the app bar to slide in and out of view based on the scrolling action of certain views within the view hierarchy. One element within the layout hierarchy shown in Figure 56-4 is the ConstraintLayout. To achieve this coordinated behavior, it is necessary to set properties on the element on which scrolling takes place and the elements with which the scrolling is to be coordinated.

On the scrolling element (in this case, the RecyclerView), the android:layout_behavior property must be set to appbar_scrolling_view_behavior. Within the content_main.xml file, locate the top-level ConstraintLayout element and note that this property has been set by default:

<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" >Code language: HTML, XML (xml)

Next, open the activity_main.xml file in the layout editor, switch to Code mode, and locate the AppBarLayout element. Note that the only child of AppBarLayout in the view hierarchy is the Toolbar. To make the toolbar react to the scroll events occurring in the RecyclerView, the app:layout_scrollFlags property must be set on this element. The value assigned to this property will depend on the nature of the interaction required and must consist of one or more of the following:

  • scroll – Indicates that the view is to be scrolled off the screen. If this is not set, the view will remain pinned at the top of the screen during scrolling events.
  • enterAlways – When used with the scroll option, an upward scrolling motion will cause the view to retract. Any downward scrolling motion in this mode will cause the view to reappear.
  • enterAlwaysCollapsed – When set on a view, that view will not expand from the collapsed state until the downward scrolling motion reaches the limit of the list. If the minHeight property is set, the view will appear during the initial scrolling motion but only until the minimum height is reached. It will then remain at that height and will not expand fully until the top of the list is reached. Note that this option only works when used with both the enterAlways and scroll options. For example:
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
android:minHeight="20dp"Code language: HTML, XML (xml)
  • exitUntilCollapsed – When set, the view will collapse during an upward scrolling motion until the minHeight threshold is met. At that point, it will remain at that height until the scroll direction changes.

For this example, the scroll and enterAlways options will be set on the Toolbar as follows:

<com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_scrollFlags="scroll|enterAlways" />Code language: HTML, XML (xml)

With the appropriate properties set, rerun the app and make an upward scrolling motion in the RecyclerView list. This should cause the toolbar to collapse out of view (Figure 56-5). A downward scrolling motion should cause the toolbar to reappear.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

Figure 56-5

Introducing the Collapsing Toolbar Layout

The CollapsingToolbarLayout container enhances the standard toolbar by providing a greater range of options and control over the collapsing of the app bar and its children in response to coordinated scrolling actions. The CollapsingToolbarLayout class is intended to be added as a child of the AppBarLayout. It provides features such as automatically adjusting the font size of the toolbar title as the toolbar collapses and expands. A parallax mode allows designated content in the app bar to fade from view as it collapses, while a pin mode allows elements of the app bar to remain in a fixed position during the contraction.

A scrim option is also available to designate the color to which the toolbar should transition during the collapse sequence.

To see these features in action, the app bar contained in the activity_main.xml file will be modified to use the CollapsingToolbarLayout class together with the addition of an ImageView to demonstrate the effect of parallax mode better. The new view hierarchy that makes use of the CollapsingToolbarLayout is represented by the diagram in Figure 56-6:

Figure 56-6

Load the activity_main.xml file into the Layout Editor tool in Code mode and modify the layout so that it reads as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">
 
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">
 
        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|enterAlways"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginBottom="30dp"
            app:expandedTitleMarginStart="15dp"
            app:expandedTitleMarginEnd="64dp">
 
            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax"
                android:src="@drawable/appbar_image" />
 
            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"
                app:layout_collapseMode="pin" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
 
    </com.google.android.material.appbar.AppBarLayout>
 
    <include
        android:id="@+id/contentMain"
        layout="@layout/content_main" />
 
</androidx.coordinatorlayout.widget.CoordinatorLayout>Code language: HTML, XML (xml)

In addition to adding the new elements to the layout above, the background color property setting has been removed. This change has the advantage of providing a transparent toolbar allowing more of the image to be visible in the app bar.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

Using the file system navigator for your operating system, locate the appbar_image.jpg image file in the project_ icons folder of the code sample download for the book and copy it. Right-click on the app -> res -> drawable entry in the Project tool window and select Paste from the resulting menu. When run, the app bar should appear as illustrated in Figure 56-7:

Figure 56-7

Scrolling the list upwards will cause the app bar to collapse gradually. During the contraction, the image will fade to the color defined by the scrim property while the title text font size reduces at a corresponding rate until only the toolbar is visible:

Figure 56-8

The toolbar has remained visible during the initial stages of the scrolling motion (the toolbar will also recede from view if the upward scrolling motion continues) as the flexible area collapses because the toolbar element in the activity_main.xml file was configured to use pin mode:

app:layout_collapseMode="pin"Code language: HTML, XML (xml)

Had the collapse mode been set to parallax, the toolbar would have retracted along with the image view.

Continuing the upward scrolling motion will cause the toolbar also to collapse, leaving only the status bar visible:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

Figure 56-9

Since the scroll flags property for the CollapsingToolbarLayout element includes the enterAlways option, a downward scrolling motion will cause the app bar to expand again.

To fix the toolbar in place so that it no longer recedes from view during the upward scrolling motion, replace enterAlways with exitUntilCollapsed in the layout_scrollFlags property of the CollapsingToolbarLayout element in the activity_main.xml file as follows:

<com.google.android.material.appbar.CollapsingToolbarLayout
    android:id="@+id/collapsing_toolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_scrollFlags="scroll|exitUntilCollapsed"
    android:fitsSystemWindows="true"
    app:expandedTitleMarginBottom="30dp"
    app:expandedTitleMarginStart="15dp"
    app:expandedTitleMarginEnd="64dp">Code language: HTML, XML (xml)

Changing the Title and Scrim Color

As a final task, edit the MainActivity.kt file and add some code to the onCreate() method to change the title text on the collapsing layout manager instance and to set a different scrim color (note that the scrim color may also be set within the layout resource file):

package com.ebookfrenzy.carddemo
.
.
import android.graphics.Color
.
.
class MainActivity : AppCompatActivity() {
.
.
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
 
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
 
        setSupportActionBar(binding.toolbar)
 
        binding.collapsingToolbar.title = "My Toolbar Title"
        binding.collapsingToolbar.setContentScrimColor(Color.GREEN)
 
        layoutManager = LinearLayoutManager(this)
        binding.contentMain.recyclerView.layoutManager = layoutManager
        adapter = RecyclerAdapter()
        binding.contentMain.recyclerView.adapter = adapter
    }
.
.
}Code language: Kotlin (kotlin)

Run the app one last time and note that the new title appears in the app bar and that scrolling now causes the toolbar to transition to green as it retracts from view.

Summary

The app bar at the top of most Android apps can consist of several elements, including a toolbar, tab layout, and image view. When embedded in a CoordinatorLayout parent, several different options are available to control how the app bar behaves in response to scrolling events in the main content of the activity. For greater control over this behavior, the CollapsingToolbarLayout manager provides a range of additional levels of control over how the app bar content expands and contracts relative to scrolling activity.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook