Android Collapsing Toolbar With Image And RecyclerView Example

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 component, one is ImageView the other is Toolbar.

1. Android Collapsing Toolbar Example Overview.

android collapsing toolbar with image and recyclerview example

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.

Below AppBarLayout is a RecyclerView, it will display some images in vertical direction use a linear layout manager. When click each image, a Snackbar will popup from screen bottom. When the RecyclerView scroll, you can see the collapsing toolbar expanded and collapsed.

The floating action button is anchored at the RecyclerView component bottom end corner. When click it a Toast message will popup.

Below is this example java files.

android collapsing toolbar layout example java files

You need add below dependency library in 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.

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.

Saved in app / res / layout folder.

READ :   Android Material Design Toolbar Example

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.

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;

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

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.

Saved in app / res / layout folder.

READ :   How To Use Android FileProvider To Share Files Between Apps

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.

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;

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

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.

CollapsingRecyclerViewItem.java

package com.dev2qa.example.material_design.toolbar;

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

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.

Saved in app / manifests folder.

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 below error message will be thrown.

Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor.

already has action bar error when use toolbar to replace actionbar

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>

 

(Visited 5,282 times, 7 visits today)

1 Comment


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

    Reply

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.