Android Collapsing Toolbar With Image And RecyclerView Example

The class android.support.design.widget.CollapsingToolbarLayout is used to wrap android.support.v7.widget.Toolbar to make the Toolbar collapsable and more beautiful. Generally, CollapsingToolbarLayout contains two child components, one is ImageView the other is Toolbar.

1. Android Collapsing Toolbar Example Overview.

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

  1. In this example, there is a Toolbar wrapped by CollapsingToolbarLayout. The CollapsingToolbarLayout is used as direct child of AppBarLayout. And AppBarLayout is child of CoordinatorLayout.
  2. Below AppBarLayout is a RecyclerView, it will display some images in the vertical direction using a linear layout manager.
  3. When clicking each image, a Snackbar will pop up from the screen bottom.
  4. When the RecyclerView scrolls, you can see the collapsing toolbar expanded and collapsed.
  5. The floating action button is anchored at the RecyclerView component bottom end corner. When clicking it a Toast message will pop up.
  6. Below are the example java files.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\EXAMPLE\APP\SRC\MAIN\JAVA\COM\DEV2QA\EXAMPLE\MATERIAL_DESIGN\TOOLBAR
        CollapsingRecyclerViewDataAdapter.java
        CollapsingRecyclerViewHolder.java
        CollapsingRecyclerViewItem.java
        CollapsingToolbarLayoutActivity.java
        ToolbarActivity.java
  7. You need to add the below dependency library in the build.gradle file in this example.
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support:recyclerview-v7:26.+'
    

2. Main Activity.

  1. CollapsingToolbarLayoutActivity.java
    package com.dev2qa.example.material_design.toolbar;
    
    import android.os.Bundle;
    import android.support.design.widget.CollapsingToolbarLayout;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v7.app.ActionBar;
    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.MenuItem;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import com.dev2qa.example.R;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class CollapsingToolbarLayoutActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_collapsing_toolbar_layout);
    
            setTitle("dev2qa.com - Android Collapsing Toolbar Example.");
    
            // Get Toolbar component.
            Toolbar toolbar = (Toolbar)findViewById(R.id.collapsing_toolbar);
            // Use Toolbar to replace default activity action bar.
            setSupportActionBar(toolbar);
    
            ActionBar actionBar = getSupportActionBar();
            if(actionBar!=null)
            {
                // Display home menu item.
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
    
            // Set collapsing tool bar title.
            CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar_layout);
            collapsingToolbarLayout.setTitle("Collapsing Tool Bar");
    
            // Set collapsing tool bar image.
            ImageView collapsingToolbarImageView = (ImageView)findViewById(R.id.collapsing_toolbar_image_view);
            collapsingToolbarImageView.setImageResource(R.drawable.img1);
    
            // Create the RecyclerView items list.
            List<CollapsingRecyclerViewItem> itemList = new ArrayList<CollapsingRecyclerViewItem>();
            itemList.add(new CollapsingRecyclerViewItem(R.drawable.car_audi));
            itemList.add(new CollapsingRecyclerViewItem(R.drawable.car_benz));
            itemList.add(new CollapsingRecyclerViewItem(R.drawable.car_bmw));
            itemList.add(new CollapsingRecyclerViewItem(R.drawable.car_future));
            itemList.add(new CollapsingRecyclerViewItem(R.drawable.car_land_rover));
            itemList.add(new CollapsingRecyclerViewItem(R.drawable.car_jeep));
    
            // Create RecyclerView.
            RecyclerView recyclerView = (RecyclerView)findViewById(R.id.collapsing_toolbar_recycler_view);
            // Create the linear layout manager.
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            // Use above layout manager for RecyclerView..
            recyclerView.setLayoutManager(linearLayoutManager);
    
            // Create recycler view data adapter with item list.
            CollapsingRecyclerViewDataAdapter dataAdapter = new CollapsingRecyclerViewDataAdapter(itemList);
            // Set RecyclerView data adapter.
            recyclerView.setAdapter(dataAdapter);
    
            // When click floating action button, popup a Toast message.
            FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.collapsing_toolbar_floating_action_button);
            floatingActionButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(), "You click floating action button.", Toast.LENGTH_LONG).show();
                }
            });
        }
    
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int itemId = item.getItemId();
    
            // When user click home menu item then quit this activity.
            if(itemId==android.R.id.home)
            {
                finish();
            }
            return super.onOptionsItemSelected(item);
        }
    }

3. Main Activity Layout Xml File.

  1. Saved in app/res/layout folder.
  2. activity_collapsing_toolbar_layout.xml
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.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"
        tools:context="com.dev2qa.example.material_design.toolbar.CollapsingToolbarLayoutActivity">
    
        <android.support.design.widget.AppBarLayout
            android:id="@+id/collapsing_toolbar_appbarlayout"
            android:layout_width="match_parent"
            android:layout_height="200dp">
    
            <!--app:contentScrim : The Toolbar color when the collapsing toolbar is collapsed.-->
            < android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar_layout"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:contentScrim="@color/colorGreen">
    
                <!--app:layout_collapseMode : parallax means an animation effect, pin means fixed.-->
                <ImageView
                    android:id="@+id/collapsing_toolbar_image_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
    
                    android:scaleType="centerCrop"
                    app:layout_collapseMode="parallax"/>
    
                <android.support.v7.widget.Toolbar
                    android:id="@+id/collapsing_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"/>
    
            </android.support.design.widget.CollapsingToolbarLayout>
    
    
        </android.support.design.widget.AppBarLayout>
    
        <!--app:layout_behavior attribute value settings make app tool bar appear while RecyclerView scroll. -->
        <android.support.v7.widget.RecyclerView
            android:id="@+id/collapsing_toolbar_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    
        <!--app:layout_anchor attribute value is the component id that this floating action button will anchor at. app:layout_anchorGravity configures where the floating action button will located at.->
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/collapsing_toolbar_floating_action_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="19dp"
            android:src="@drawable/transparent_check_icon"
            app:layout_anchor="@id/collapsing_toolbar_recycler_view"
            app:layout_anchorGravity="bottom|end"/>
    
    </android.support.design.widget.CoordinatorLayout>

4. RecyclerView Data Adapter.

  1. CollapsingRecyclerViewDataAdapter.java
    package com.dev2qa.example.material_design.toolbar;
    
    import android.support.design.widget.Snackbar;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    
    import com.dev2qa.example.R;
    
    import java.util.List;
    
    
    public class CollapsingRecyclerViewDataAdapter extends RecyclerView.Adapter<CollapsingRecyclerViewHolder> {
    
        private List<CollapsingRecyclerViewItem> viewItemList;
    
        public CollapsingRecyclerViewDataAdapter(List<CollapsingRecyclerViewItem> viewItemList) {
            this.viewItemList = viewItemList;
        }
    
        @Override
        public CollapsingRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // Get LayoutInflater object.
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            // Inflate the RecyclerView item layout xml.
            final View itemView = layoutInflater.inflate(R.layout.activity_collapsing_toolbar_layout_recycler_view_item, parent, false);
    
            final ImageView imageView = (ImageView)itemView.findViewById(R.id.collapsing_toolbar_recycler_view_item_image);
            // Popup a Snackbar at screen bottom when click image.
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Snackbar snackbar = Snackbar.make(v, "You click this image.", Snackbar.LENGTH_LONG);
                    snackbar.show();
                }
            });
    
            // Create and return collapsing Recycler View Holder object.
            CollapsingRecyclerViewHolder ret = new CollapsingRecyclerViewHolder(itemView);
            return ret;
        }
    
        @Override
        public void onBindViewHolder(CollapsingRecyclerViewHolder holder, int position) {
            if(viewItemList!=null) {
                // Get item dto in list.
                CollapsingRecyclerViewItem viewItem = viewItemList.get(position);
    
                if(viewItem != null) {
                    // Set car image resource id.
                    holder.getImageView().setImageResource(viewItem.getImageId());
                }
            }
        }
    
        @Override
        public int getItemCount() {
            int ret = 0;
            if(viewItemList!=null)
            {
                ret = viewItemList.size();
            }
            return ret;
        }
    }

5. RecyclerView Item Layout Xml File.

  1. Saved in app/res/layout folder.
  2. activity_collapsing_toolbar_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="10dp"
        app:cardCornerRadius="8dp">
    
        <LinearLayout
            android:id="@+id/collapsing_toolbar_recycler_view_item"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <ImageView
                android:id="@+id/collapsing_toolbar_recycler_view_item_image"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:scaleType="centerCrop"/>
    
        </LinearLayout>
    
    </android.support.v7.widget.CardView>

6. RecyclerView View Holder.

  1. CollapsingRecyclerViewHolder.java
    package com.dev2qa.example.material_design.toolbar;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.ImageView;
    
    import com.dev2qa.example.R;
    
    public class CollapsingRecyclerViewHolder extends RecyclerView.ViewHolder {
    
        private ImageView imageView = null;
    
        public CollapsingRecyclerViewHolder(View itemView) {
            super(itemView);
    
            if(itemView != null)
            {
                imageView = (ImageView)itemView.findViewById(R.id.collapsing_toolbar_recycler_view_item_image);
            }
        }
    
        public ImageView getImageView() {
            return imageView;
        }
    }

7. RecyclerView Item DTO.

  1. CollapsingRecyclerViewItem.java
    package com.dev2qa.example.material_design.toolbar;
    
    public class CollapsingRecyclerViewItem {
    
        // car image resource id.
        private int imageId;
    
        public CollapsingRecyclerViewItem(int imageId) {
            this.imageId = imageId;
        }
    
        public int getImageId() {
            return imageId;
        }
    
        public void setImageId(int imageId) {
            this.imageId = imageId;
        }
    }

8. Android Manifest Xml File.

  1. Saved in app/manifests folder.
  2. Please note the activity android: theme property value, because we will use Toolbar to replace ActionBar, so we should use a NoActionbar theme for this activity. Otherwise, the below error message will be thrown.
    Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor.
  3. AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dev2qa.example">
    
        <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.toolbar.CollapsingToolbarLayoutActivity"
            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>
    
    </manifest>
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Sanjot
Sanjot

I am using Calenderview instead of Image view it is not working 🙁
Could you please help me out

1
0
Would love your thoughts, please comment.x
()
x