Android AppBarLayout And Toolbar Example

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

1. How To Control Android App Toolbar Show / Hide Behavior.

  1. Wrapped by AppBarLayout, the Toolbar will be hidden when the user scrolls RecyclerView down, and it will be shown again when the user scrolls RecyclerView up. You can set the behavior by configuring Toolbar‘s app:layout_scrollFlag property value as below.
    <android.support.v7.widget.Toolbar 
        ......
        app:layout_scrollFlags="scroll|snap|enterAlways"
        ...... 
    />
  2. The Toolbar property app:layout_scrollFlags‘s value can be followings.
  3. scroll: Scroll means when the RecyclerView scrolls up, the Toolbar will scroll up also and be hidden.
  4. 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.
  5. enterAlways: This means when RecyclerView scrolls down, the Toolbar will scroll down and display again.

2. Scroll RecyclerView To Show / Hide Toolbar Example.

    1. In this example, there is a Toolbar and a RecyclerView on the screen. The Toolbar contains two menu items Add and Delete. The RecyclerView use LinearLayoutManager to list some car image and text.
    2. When clicking the Add menu item, it will add a car to the list randomly, when clicking the Delete menu item, it will automatically delete a car in the list also.

Below is the screen without use AppBarLayout to wrap Toolbar.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/FRkDIDS05MI

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

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/8DarKKFuv9A

3. Example Files.

  1. There are four java files, two layout XML files, and one menu XML file in this example.
  2. Java files are saved in the app/java folder.
    AppBarLayoutActivity.java
    
    AppBarLayoutRecyclerViewDataAdapter.java
    
    AppBarLayoutRecyclerViewItem.java
    
    AppBarLayoutRecyclerViewItemHolder.java
    
    
  3. Layout XML files are saved in the app/res/layout folder.
    activity_app_bar_layout.xml
    
    activity_app_bar_layout_recycler_view_item.xml
    
  4. Toolbar menu xml file is saved in app / res / menu folder.
    activity_app_bar_layout_tool_bar_menu.xml
  5. The android project AndroidManifest.xml file is saved in the app/manifests folder.
    AndroidManifest.xml

4. Main Activity.

  1. 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.

  1. AppBarLayoutRecyclerViewItem.java
    package com.dev2qa.example.material_design.app_bar_layout;
    
    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.

  1. 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;
    
    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.

  1. 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;
    
    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.

  1. This file is saved in the app/res/layout folder. The RecyclerView‘s app:layout_behavior attribute points out that when RecyclerView scrolls, AppBar will also scroll accordingly.
  2. 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.

  1. Saved in app/res/layout folder.
  2. 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.

  1. Saved in app/res/menu folder.
  2. 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.

  1. Saved in app/manifests folder.
  2. AndroidManifest.xml
    <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
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x