Android AppBarLayout And Toolbar Example

android.support.design.widget.AppBarLayout is used to wrap android.support.v7.widget.Toolbar component. It can make Toolbar to avoid overlapped by ListView or RecyclerView controls in the screen.

1. How To Control Toolbar Show / Hide Behavior.

Wrapped by AppBarLayout, the Toolbar will be hidden when user scroll RecyclerView down, and it will be shown again when user scroll RecyclerView up. You can set the behavior by configure Toolbar’s app:layout_scrollFlag property value as below.

<android.support.v7.widget.Toolbar
    ......
    app:layout_scrollFlags="scroll|snap|enterAlways"
    ...... />

app:layout_scrollFlags value:

  1. scroll : Scroll means when the RecyclerView scroll up, Toolbar will scroll up also and hidden.
  2. snap : Snap indicates that when Toolbar is not fully hidden or displayed, it will automatically select whether it is hidden or displayed on the basis of the current rolling distance.
  3. enterAlways : This means when RecyclerView scroll down, Toolbar will scroll down and display again.

2. Scroll RecyclerView To Show / Hide Toolbar Example.

In this example, there is a Toolbar and a RecyclerView in the screen. The Toolbar contains two menu item Add and Delete. The RecyclerView use LinearLayoutManager to list some car image and text.

When click the Add menu item, it will add a car in the list randomly, when click the Delete menu item, it will automatically delete a car in the list also.

Below is the screen without use AppBarLayout to wrap Toolbar.

android toolbar do not use appbarlayout

Below is the screen that use AppBarLayout to wrap Toolbar component.

android wrap toolbar with appbarlayout

3. Example Files.

There are four java files, two layout xml files and one menu xml file in this example.

Java files is saved in app / java folder.

appbarlayout toolbar example java files
Layout xml files is saved in app / res / layout folder.

appbarlayout toolbar example layout xml files
Toolbar menu xml file is saved in app / res / menu folder.

appbarlayout toolbar example menu xml files

4. Main Activity.

AppBarLayoutActivity.java

package com.dev2qa.example.material_design.app_bar_layout;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.dev2qa.example.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AppBarLayoutActivity extends AppCompatActivity {

    private List<AppBarLayoutRecyclerViewItem> carList = null;

    private RecyclerView carRecyclerView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_bar_layout);

        setTitle("dev2qa.com - Android AppBarLayout Example.");

        Toolbar toolbar = (Toolbar)findViewById(R.id.appbarlayout_tool_bar);
        toolbar.setTitle("This is toolbar.");
        setSupportActionBar(toolbar);

        createCarListUseRecyclerView();
    }


    // This method shows how to customize SimpleAdapter to show image and text in ListView.
    private void createCarListUseRecyclerView()
    {
        if(carList == null) {

            // Initialise car list.
            carList = new ArrayList<AppBarLayoutRecyclerViewItem>();

            carList.add(new AppBarLayoutRecyclerViewItem("Audi", R.drawable.car_audi));
            carList.add(new AppBarLayoutRecyclerViewItem("BMW", R.drawable.car_bmw));
            carList.add(new AppBarLayoutRecyclerViewItem("Benz", R.drawable.car_benz));
            carList.add(new AppBarLayoutRecyclerViewItem("Jeep", R.drawable.car_jeep));
            carList.add(new AppBarLayoutRecyclerViewItem("Land Rover", R.drawable.car_land_rover));
            carList.add(new AppBarLayoutRecyclerViewItem("Future", R.drawable.car_future));
        }

        // Create the recyclerview.
        carRecyclerView = (RecyclerView)findViewById(R.id.appbarlayout_recycler_view);
        // Create the linear layout manager.
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);
        // Set layout manager.
        carRecyclerView.setLayoutManager(linearLayoutManager);

        // Create car recycler view data adapter with car item list.
        AppBarLayoutRecyclerViewDataAdapter carDataAdapter = new AppBarLayoutRecyclerViewDataAdapter(carList);
        // Set data adapter.
        carRecyclerView.setAdapter(carDataAdapter);
    }

    /* Invoked when create tool bar menu. */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Get menu inflater.
        MenuInflater menuInflater = getMenuInflater();

        // Use app bar layout menu to inflate the tool bar.
        menuInflater.inflate(R.menu.activity_app_bar_layout_tool_bar_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Invoked when user click the menu in tool bar. */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Get menu item id.
        int menuItemId = item.getItemId();

        // Get item list size.
        int size = carList.size();

        // Get an item index randomly.
        Random random = new Random();
        int randomIndex = random.nextInt(size);

        // If add menu is clicked.
        if(menuItemId == R.id.appbarlayout_add_car_menu)
        {
            // Get random item.
            AppBarLayoutRecyclerViewItem randomItem = carList.get(randomIndex);
            // Add the item in car list.
            carList.add(randomItem);
            // Get new car list size.
            int carListSize = carList.size();
            // Notify recycler view data adapter a new item has been added.
            carRecyclerView.getAdapter().notifyItemInserted(carListSize - 1);

            Toast.makeText(this, "A car has been added at the bottom of the list.", Toast.LENGTH_SHORT).show();
        }else if(menuItemId == R.id.appbarlayout_delete_car_menu)
        {
            // Remove the random selected item.
            carList.remove(randomIndex);
            // Get the car list size again.
            int carListSize = carList.size();
            // Avoid index out of bounds exception.
            if(randomIndex > carListSize - 1)
            {
                randomIndex = carListSize - 1;
            }
            // Notify recycler view an item has been deleted.
            carRecyclerView.getAdapter().notifyItemRemoved(randomIndex);

            Toast.makeText(this, "A car has been removed from the list.", Toast.LENGTH_SHORT).show();
        }

        return super.onOptionsItemSelected(item);
    }
}

5. RecyclerView Item Java File.

AppBarLayoutRecyclerViewItem.java

package com.dev2qa.example.material_design.app_bar_layout;

/**
 * Created by Jerry on 3/18/2018.
 */

public class AppBarLayoutRecyclerViewItem {

    // Save car name.
    private String carName;

    // Save car image resource id.
    private int carImageId;

    public AppBarLayoutRecyclerViewItem(String carName, int carImageId) {
        this.carName = carName;
        this.carImageId = carImageId;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public int getCarImageId() {
        return carImageId;
    }

    public void setCarImageId(int carImageId) {
        this.carImageId = carImageId;
    }
}

6. RecyclerView Item Holder Java File.

AppBarLayoutRecyclerViewItemHolder.java

package com.dev2qa.example.material_design.app_bar_layout;

import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dev2qa.example.R;

/**
 * Created by Jerry on 3/18/2018.
 */

public class AppBarLayoutRecyclerViewItemHolder extends ViewHolder {

    private TextView carTitle = null;

    private ImageView carImage = null;

    public AppBarLayoutRecyclerViewItemHolder(View itemView) {
        super(itemView);

        if(itemView != null)
        {
            carTitle = (TextView)itemView.findViewById(R.id.appbarlayout_view_item_title);

            carImage = (ImageView)itemView.findViewById(R.id.appbarlayout_view_item_image);
        }
    }

    public TextView getCarTitle() {
        return carTitle;
    }

    public ImageView getCarImage() {
        return carImage;
    }
}

7. RecyclerView Data Adapter Java File.

AppBarLayoutRecyclerViewDataAdapter.java

package com.dev2qa.example.material_design.app_bar_layout;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dev2qa.example.R;

import java.util.List;

/**
 * Created by Jerry on 3/18/2018.
 */

public class AppBarLayoutRecyclerViewDataAdapter extends RecyclerView.Adapter<AppBarLayoutRecyclerViewItemHolder> {

    private List<AppBarLayoutRecyclerViewItem> carList;

    public AppBarLayoutRecyclerViewDataAdapter(List<AppBarLayoutRecyclerViewItem> carList) {
        this.carList = carList;
    }

    @Override
    public AppBarLayoutRecyclerViewItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Get LayoutInflater object.
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        // Inflate the RecyclerView item layout xml.
        View carItemView = layoutInflater.inflate(R.layout.activity_app_bar_layout_recycler_view_item, parent, false);

        // Create and return our custom Car Recycler View Item Holder object.
        AppBarLayoutRecyclerViewItemHolder ret = new AppBarLayoutRecyclerViewItemHolder(carItemView);
        return ret;
    }

    @Override
    public void onBindViewHolder(AppBarLayoutRecyclerViewItemHolder holder, int position) {
        if(carList!=null) {
            // Get car item dto in list.
            AppBarLayoutRecyclerViewItem carItem = carList.get(position);

            if(carItem != null) {
                // Set car item title.
                holder.getCarTitle().setText(carItem.getCarName());
                // Set car image resource id.
                holder.getCarImage().setImageResource(carItem.getCarImageId());
            }
        }
    }

    @Override
    public int getItemCount() {
        int ret = 0;
        if(carList!=null)
        {
            ret = carList.size();
        }
        return ret;
    }
}

8. Main Activity Layout Xml File.

This file is saved in app / res / layout folder. Please note the red bold line in this file. The RecyclerView’s app:layout_behavior attribute point out that when RecyclerView scroll, AppBar will also scroll accordingly.

READ :   Android Radio Button Example

activity_app_bar_layout.xml

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/appbarlayout_tool_bar"
            android:background="@color/colorPrimary"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|snap|enterAlways"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/appbarlayout_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

9. RecyclerView Item Layout Xml File.

Saved in app / res / layout folder.

activity_app_bar_layout_recycler_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardCornerRadius="15dp">

    <LinearLayout
        android:id="@+id/appbarlayout_view_item"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/appbarlayout_view_item_image"
            android:layout_width="match_parent"
            android:layout_height="130dp"
            android:scaleType="centerCrop"/>

        <TextView
            android:id="@+id/appbarlayout_view_item_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_marginLeft="20dp"/>

    </LinearLayout>

</android.support.v7.widget.CardView>

10. Toolbar Menu Definition Xml File.

Saved in app / res / menu folder.

activity_app_bar_layout_tool_bar_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/appbarlayout_add_car_menu"
        android:icon="@drawable/add_icon"
        android:title="Add"
        app:showAsAction="always|withText" />

    <item
        android:id="@+id/appbarlayout_delete_car_menu"
        android:icon="@drawable/delete_icon"
        android:title="Delete"
        app:showAsAction="always|withText" />

</menu>

11. Android Manifest Xml File.

Saved in app / manifests folder.

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity android:name=".material_design.app_bar_layout.AppBarLayoutActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Reference

  1. Android Material Design Toolbar Example
  2. Android CardView With Image And Text Example
  3. Android RecyclerView Example
(Visited 3,125 times, 19 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.