Browse By

How to Create Collapsing Toolbar Layout like Whatsapp in Android Application


 How to Create Collapsing Toolbar Layout like Whatsapp in Android ApplicationWe have seen previously How to Use RecyclerView with CardView in Android application. Today we will learn How to Create Collapsing Toolbar Layout like Whatsapp in Android Application.

CollapsingToolbarLayout to ensure that the toolbar itself remains pined to the top of the screen while the view collapses. 

Toolbar title will automatically appear larger when the layout is fully visible, then transition to its default size it is collapsed.

CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It is designed to be used as a direct child of a AppBarLayout. 

If you scroll the listview automatically toolbar gets hidden, like whatsapp.

Direct Download Full Source Code

 

 

How to Create Collapsing Toolbar Layout like Whatsapp in Android Application

1. First, add Support Design Library, Recyclerview and Cardview in gradle:

compile 'com.android.support:design:22.2.1'
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:22.2.0'

2. In activity_main ,coordinator layout out will be the root element in layout file. Then in appbar layout add collapsing toobar laytout and toolbar and place your image inside collapsing toolbar. Add Recycler view and floating button outside appbar layout.

<android.support.design.widget.CoordinatorLayout 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="match_parent"
    android:fitsSystemWindows="true">

   	<android.support.design.widget.AppBarLayout
        	android:id="@+id/app_bar_layout"
       	android:layout_width="match_parent"
       	android:layout_height="wrap_content"
       	android:fitsSystemWindows="true"
       	android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

	<android.support.design.widget.CollapsingToolbarLayout
       	android:id="@+id/collapsing_toolbar"
        	android:layout_width="match_parent"
       	android:layout_height="match_parent"
        	android:fitsSystemWindows="true"
        	app:contentScrim="?attr/colorPrimary"
        	pp:layout_scrollFlags="scroll|exitUntilCollapsed">

		 <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/nature"
                app:layout_collapseMode="parallax" />

		<android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
                android:title="Collapsing Toolbar"
                app:layout_collapseMode="pin" />
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

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

  	  <android.support.design.widget.FloatingActionButton
        	  android:id="@+id/fab"
        	  android:layout_width="wrap_content"
        	  android:layout_height="wrap_content"
        	  android:layout_margin="16dp"
        	  android:clickable="true"
        	  android:src="@drawable/ic_edit"
        	  app:layout_anchor="@id/recyclerView"
        	  app:layout_anchorGravity="bottom|right|end" />
	  </android.support.design.widget.CoordinatorLayout>


3. 
Now we have to create layout for CardView to hold it in adapter. Create card_view.xml in layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    card_view:cardPreventCornerOverlap="false"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="2dp"
    card_view:contentPadding="10dp">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/rel">

        <ImageView
                android:id="@+id/cardimage"
                android:layout_width="50dp"
                android:layout_height="50dp"
        	android:scaleType="fitCenter"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"/>

         <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="title"
                android:layout_marginLeft="10dp"
                android:textStyle="bold"
                android:textSize="20sp"
                android:id="@+id/cardtitle"
                android:layout_gravity="center_vertical"/>
        </LinearLayout>
</android.support.v7.widget.CardView>

 

4. Create model class Flower.java and add name and int id ( for drawables) and crate constructor of Model class.

package com.vrs.material_collpasingtoolbar;
/**
 * Created by vrs on 7/10/15.
 */
public class Flower 
{
    String name;
    int id;

    public Flower(String name, int id) {
        this.name = name;
        this.id = id;
    }
    public String getName(){
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    } 
}


5. Now for attaching adapter to recyclerview, create java file CardAdapter.java and inflate 
card_view layout in onCreateViewHolder method.

package com.vrs.material_collpasingtoolbar;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by vrs on 3/9/15.
 */
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
    List<Flower> list = new ArrayList<>();
    public CardAdapter(List<Flower> list) {
        this.list = list;
    }
        @Override
    public int getItemCount() {
        return list.size();
    }
    public Flower getItem(int i) {
        return list.get(i);
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view, parent, false);
        return new ViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.Flower=getItem(position);
        holder.cardtitle.setText(list.get(position).name);
        holder.cardimage.setImageResource(list.get(position).id);
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView cardimage;
        TextView cardtitle;
        Flower Flower;
        public ViewHolder(View itemView) {
            super(itemView);
            cardimage = (ImageView) itemView.findViewById(R.id.cardimage);
            cardtitle = (TextView) itemView.findViewById(R.id.cardtitle);
        }
    }
}

 

6. Now in MainActivity.java,set content view to R.layout.activity_main. Initialize toolbar, floatingAction button and collapsing toolbar layout in it.

Create method initializeData() and create array list of flowers in it and call the constructor of Flower class and put title and image into it. Call this method before setting adapter.

package com.vrs.material_collpasingtoolbar;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
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.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {

	//ui control
	Toolbar toolbar;
	CollapsingToolbarLayout collapsingToolbarLayout;
	RecyclerView recyclerView;    
	FloatingActionButton floatingActionButton;

	CardAdapter adapter;
	List<Flower> flowers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
	collapsingToolbarLayout = (CollapsingToolbarLayout) 	findViewById(R.id.collapsing_toolbar);
	recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
	toolbar = (Toolbar) findViewById(R.id.toolbar);
	floatingActionButton=(FloatingActionButton)findViewById(R.id.fab);

	collapsingToolbarLayout.setTitle("Demo");
	setSupportActionBar(toolbar);

       //recyclerview
	LinearLayoutManager llm = new LinearLayoutManager(this);
	llm.setOrientation(LinearLayoutManager.VERTICAL);
	recyclerView.setLayoutManager(llm);
	recyclerView.setHasFixedSize(true);

	initializeData();

	adapter = new CardAdapter(flowers);

	//set adapter
	recyclerView.setAdapter(adapter);
	floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Snackbar.make(v, "You clicked on the fab", Snackbar.LENGTH_SHORT).show();
          }
       });
    }
    private void initializeData() {
        flowers = new ArrayList<>();
        flowers.add(new Flower("Flower 1", R.drawable.image2));
        flowers.add(new Flower("Flower 2", R.drawable.images3));
        flowers.add(new Flower("Flower 3", R.drawable.images4));
        flowers.add(new Flower("Flower 4", R.drawable.images6));
        flowers.add(new Flower("Flower 5", R.drawable.images7));
        flowers.add(new Flower("Flower 6", R.drawable.images10));
        flowers.add(new Flower("Flower 7", R.drawable.images11));
        flowers.add(new Flower("Flower 8", R.drawable.images12));
        flowers.add(new Flower("Flower 9", R.drawable.images14));
        flowers.add(new Flower("Flower 10", R.drawable.images17));
        flowers.add(new Flower("Flower 11", R.drawable.images18));
        flowers.add(new Flower("Flower 12", R.drawable.index));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

 

7. Now execute application

I hope you like this article. Share your views to to improve content. Happy Coding !!!

Download Full Source Code

 

  • harsha

    am implementing coordinate layout with title and image and options menu with like and dislike icon when i collapse the toolbar and change the status of the like unlike image the toolbar title is invisible please help me.

    • Bhavika Solanki

      Can you share your code snippet , so that I can review your code in detail and can give you more specific solution

  • Vipul Bambhaniya

    Hello sir. I m using Eclipse. can you give me a link for library for Collapsing Toolbar Layout.

    • Bhavika Solanki

      To achieve that, You have to import support design library in eclipse. Browse your sdk directory and look for following path /extras/android/support/v7/design. And then import design folder as normal project in eclipse. Right click on Project > Properties > Android and mark it as library, via the “Is Library” checkbox. Then, you can attach it to your application that wishes to use the library.

      • Vipul Bambhaniya

        Thank you so much :-). I will try it.

  • Pingback: Android - Create Circular Reveal Animation And Ripple Effect like Whatsapp - Pulse7()

  • Srinivas Kalyani

    Hi, this was a great tutorial. Could you please tell me how to add a subtitle in the collapsingtoolbarlayout?

    • Bhavika Solanki

      For adding subtitle, you have to implement custom layout behaviour.

  • Pingback: Android & iOS Application Development | Just another My blog Sites site()

  • Pingback: Android Developers | Just another My blog Sites site()

  • Bhavika Solanki

    For adding subtitles, you have to implement custom layout behaviour.

  • Pingback: Android - Create Android project in Android Studio 2.0()

  • Wiliam

    Hi boys, when I scrolled all itens for down, my CollapsingToolbarLayout not down together

  • Wiliam

    Hi,
    When I give a slap back to the top of the list collapsing toolbar not automatically expands.
    I need the collapsingtoolbar has the same behavior playstore

  • Manoj Yadav

    hi
    is it working in eclipse also
    bcoz i developd my app in eclipse

    • Davidoff

      Abandon Eclipse right now and convert the project to Android Studio… (right now!) I don’t think I will have to give you further explanation, you will open your eyes once you will do it.

      • Manoj Yadav

        thanks
        but its working in eclipse also i implemented.

  • Shabbir Dhangot

    Hello Vimal sir,

    you forgot ‘a’ on line 10 activity_main.xml