Recycler View Layout Adapter with Header Android Tutorial

Header in Recycler View adapter is very important part of the view, It is the place where you want to add a title or heading of the layout item.  So let’s create a header for our Recycler View which automatically works as we will use our adapter for creating the header for our Recycler View.  The Recycler View header will automatically fix and change the header contains depending on the input provided at the time of initializing the recycler view adapter.  I am writing this here because initially, I face lots of problem in the implementation of the header but after some research and of course on the cost of some time, I realized that it is quite easy.
I am writing this here because initially, I face lots of challenges when I was trying to add it for the first time but after some research and of course on the cost of some time, I realized that it is quite easy.

Create Project

1. Create a Project for Recycler View and select the name of the project for example here I am taking the name as HeaderViewExample, you can choose your own.

Let’s select the default option, it will take some time and default main activity will be get created.
MainActivity.java

package com.debugandroid.headerviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Dependency Injection for creating the Recycler View Header

Will not do any modification here in MainActivity.java file.Before going to next step we need to add the dependency in my default build.gradle file as given below.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'   
    compile 'com.android.support:appcompat-v7:24.2.1'  
    compile 'com.android.support:recyclerview-v7:24.2.0'
    compile 'com.android.support:cardview-v7:24.2.0'
}

Add the Recycler View Layout to layout xml

Add the Recycle view in the activity_main.xml file after removing the default text view or if you would like you can test your app as well ensures that you have done correctly till now. You can use the emulator or any other connected device using the ADB.

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"  
 android:layout_width="match_parent"   
 android:layout_height="match_parent"   
 tools:context="com.debugandroid.headerviewexample.MainActivity"> <android.support.v7.widget.RecyclerView   
  android:layout_width="match_parent"   
  android:layout_height="match_parent"   
  android:id="@+id/recyclerView">   
  </android.support.v7.widget.RecyclerView>   
 </RelativeLayout>  

Create Header Layout file header_layout.xml

We have to create the layout for our recycler view header, which will be shown on the top of the recycler view layout. In this layout, we can add the view depending on projects requirement, for example, we can add drop down button, a Text View to show heading, Image View to show the Icon or photo. Here our requirement is just to add a Text View to show the title of the layout item which will be populated inside our recycler view.

 <?xml version="1.0" encoding="utf-8"?>  
 <android.support.v7.widget.CardView   
 android:layout_width="match_parent"    
 android:layout_height="wrap_content"   
 xmlns:card_view="http://schemas.android.com/apk/res-auto"  
 card_view:cardCornerRadius="1dp"  
 android:layout_margin="2dp"    
 xmlns:android="http://schemas.android.com/apk/res/android">  
   <TextView  
    android:layout_width="match_parent"   
    android:layout_height="30dp"      
    android:layout_gravity="center"     
    android:textColor="@android:color/white"   
    android:background="@color/header"   
    android:id="@+id/header"/>  
 </android.support.v7.widget.CardView>  

Create Item Layout file

We also required item layout to display the each item in our recycler view, so for that, we have to create a layout XML file. Item layout files will look like as given below.

row_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <android.support.v7.widget.CardView   
 android:layout_width="match_parent"   
 android:layout_height="wrap_content"   
 xmlns:android="http://schemas.android.com/apk/res/android"   
 xmlns:card_view="http://schemas.android.com/apk/res-auto"   
 card_view:cardCornerRadius="1dp" android:layout_margin="2dp">  
   <TextView      
     android:layout_gravity="center"  
     android:layout_width="match_parent"  
     android:background="@color/Itemcolor"  
     android:textColor="@android:color/white"  
     android:layout_height="40dp"  
     android:id="@+id/item_name"  />  
 </android.support.v7.widget.CardView>  

Create Adapter for Recycler View

We are almost done with layout design part so as results now we have to go for the creation of the adapter for our recycler view layout.

So for creating the adapter for our layout right click on the module and created Adapter class and modify it as given below.

 package com.debugandroid.headerviewexample;  
 import android.content.Context;  
 import android.os.Bundle;  
 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.TextView;  
 import java.util.List;  
 public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {  
   private boolean isHeader;  
   private List<String> data;  
   private Context context;  
   public static final int VIEW_HEADER = 0;  
   public static final int VIEW_ITEM = 1;  
   public Adapter(Context context, List<String> data, boolean isHeader){  
     this.context=context;  
     this.data=data;  
     this.isHeader=isHeader;  
   }  
   @Override    
   public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
     if(viewType==VIEW_HEADER) {  
       return new headView(LayoutInflater.from(context).inflate(R.layout.header_layout, parent, false));  
     }  
     else     return new itemView(LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false));  
   }  
   @Override    
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {  
     if(holder instanceof headView){  
       ((headView) holder).header.setText("This is Header");  
       Log.d("Item View","Binding Item header at"+position);  
     }  
     else {  
       ((itemView) holder).itemName.setText(getName(position));  
       Log.d("Item View","Binding Item "+position);  
       ///You can add your custom code here    }  
   }  
 // to Check the number of item    
 @Override  
 public int getItemCount() {  
     int itemCount=data.size();  
     //if header is required then increase the number of count by one  
     if(isHeader){  
       itemCount=itemCount+1;  
     }  
     return itemCount;  
   }  
 /*This method is used to get the correct data depending on the type of view, if you are using the header then return number of count by adding one in actual count*/  
   public String getName(int position){  
     if(isHeader){  
       return data.get(position-1);  
     }  
     else return data.get(position);  
   }  
 /*here we are checking if header required then position must be one and return the this method return the header view */  
 @Override    
   public int getItemViewType(int position) {  
     if (isHeader && isHeader(position))  
       return VIEW_HEADER;  
     else return VIEW_ITEM;  
   }  
 //Check the position of item if item at position 0 then return true else false   
   private boolean isHeader(int position) {  
       return position == 0;  
   }  
 //This View will be used to display the header of the recylerview  
   public class headView extends RecyclerView.ViewHolder {  
     protected TextView header;  
     public headView(View v) {  
       super(v);  
       header = (TextView) v.findViewById(R.id.header);  
     }  
   }  
 //This View will be used to display the item inside recylerview  
 public class itemView extends RecyclerView.ViewHolder {  
     protected TextView itemName;  
     public itemView(View v) {  
       super(v);  
       itemName = (TextView) v.findViewById(R.id.item_name);  
     }  
   }  
 }  

Populate the Recycler View Item from Main Activity

As we have created our adapter for our recycler view. Hence we are moving to implementation part of the adapter inside our Main Activity java files. So for that, open your MainActivity.java and modify the same as given below.

 package com.debugandroid.headerviewexample;  
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.support.v7.widget.GridLayoutManager;  
 import android.support.v7.widget.RecyclerView;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class MainActivity extends AppCompatActivity {  
   private RecyclerView recyclerView;  
   private Adapter adapter;  
   private List<String> data=new ArrayList<String>();  
   @Override  protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     recyclerView= (RecyclerView) findViewById(R.id.recyclerView);  
 //Adding some dummy data here  
     for (int i=0;i<=100;i++){  
       data.add("Item "+i);  
     }  
 //using the Layout with span size of 2  
     GridLayoutManager glm = new GridLayoutManager(this, 2);  
 /* Span lookup to show the item depending on the type of view Like for header view full width*/  
     glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {  
       @Override public int getSpanSize(int position) {  
         switch (adapter.getItemViewType(position)){  
           case 0: return 2;//in case of header view  
           case 1: return 1; //in case of item view  
           default: return 2;  
         }  
       }  
     });  
     recyclerView.setLayoutManager(glm);  
     adapter=new Adapter(this,data,true);  
     recyclerView.setAdapter(adapter);  
   }  
 }  

In the above code adapter=new Adapter(this,data,true) we are initializing our adapter.  First arguments are this which represent our main activity, the second argument is some dummy data due to which our recycler view should have some view item so that we can check how our views are look and last arguments are true it is boolean variable and use to show or hide the view. Here we are giving true hence it will show the header if we give the false value it will not show the header.

Now it is time to test our stuff that we have done till now so run your app and see the output, it will look like as given in below screenshots.

Header in Recycler View

You can download the source code from here.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu