Skip to main content

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.

Comments

Popular posts from this blog

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android
Just go to the android folder and open it in separate windows. We will have the following project structure.









Create the Activity Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.
Update the project build config …