Add Sections in Android RecyclerView with SectionedRecyclerViewAdapter Library

In this tutorial, we are going to learn how to add sections in android RecyclerView with SectionedRecyclerViewAdapter library.

Android RecyclerView does not have a default way to group items together. In other to achieve this you have the write your own complete solution. It may be time consuming expect if you are doing it as part of learning process.

There is also no need to re-invent the wheel since there are few android libraries out there that do basically what you want.

If your requirement is totally different, you can build on top what is available to you.

If you are just interested to add a header section in your android RecyclerView, I will suggest you read my android tutorial on Adding Header to Android RecyclerView.

For this tutorial on Adding Sections in Android RecyclerView with SectionedRecyclerViewAdapter Library, we are going to add SectionedRecyclerViewAdapter Library as part of our project dependent libraries.

To understand what we plan to achieve in this tutorial, I have added a screen shot for the application.

sectionrecyclerview

 

CREATE NEW ANDROID PROJECT

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony F model (Android 6)

Min SDK 14

Target SDK 24

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: RecyclerViewSectionHeader

Package: com.inducesmile.recyclerviewsectionheader

Select Blank Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Build.Gradle

Since our project will depend on few third party android libraries, we are going to update our app build.gradle and sync the libraries we need. Open build.gradle file and add the code below.

apply plugin: 'com.android.application'
apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.inducesmile.recyclerviewsectionheader"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:support-v4:24.1.1'
    compile 'io.github.luizgrp.sectionedrecyclerviewadapter:sectionedrecyclerviewadapter:1.0.4'
    compile 'com.android.support:cardview-v7:24.1.1'
}

 

STRINGS.XML

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<resources>
    <string name="app_name">Android RecyclerView Header</string>
    <string name="sample">Lorem Ipsum is simply dummy text of the printing and typesetting industry</string>
</resources>

 

COLORS.XML

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
</resources>

 

HeaderRecyclerViewSection.java

We need to create a Section class. The Section class is where we will add to the content of the individual sections we will create in our android application.

In your project package folder, create a new java file and name it HeaderRecyclerViewSection.java.

This class will have a constructor with two parameters which represents the title of the section and the data source for list items of the RecyclerView widget.

Both the Item and Header get and bind methods will be overridden. Each will contain its own ViewHolder class and layout file.

Open the file and add the code below to it.

import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.List;
import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection;
public class HeaderRecyclerViewSection extends StatelessSection{
    private static final String TAG = HeaderRecyclerViewSection.class.getSimpleName();
    private String title;
    private List<ItemObject> list;
    public HeaderRecyclerViewSection(String title, List<ItemObject> list) {
        super(R.layout.header_layout, R.layout.item_layout);
        this.title = title;
        this.list = list;
    }
    @Override
    public int getContentItemsTotal() {
        return list.size();
    }
    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        return new ItemViewHolder(view);
    }
    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        ItemViewHolder iHolder = (ItemViewHolder)holder;
        iHolder.itemContent.setText(list.get(position).getContents());
    }
    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new HeaderViewHolder(view);
    }
    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        HeaderViewHolder hHolder = (HeaderViewHolder)holder;
        hHolder.headerTitle.setText(title);
    }
}

 

Layout Files for the Adapter

If you take a close look at the HeaderRecyclerViewSection class, you will see that we created two different layout file for the headerView and itemView. This is important in situations where the header will appear and look different from the items.

We are going to create the two different layout files.

 

header_layout.xml

The header_layout.xml is responsible for the header UI appearance. In this case, it will contain a single TextView widget which will server as a header title.

Create a new layout file inside the layout folder and name it header_layout.xml. Copy and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16sp"
    android:orientation="vertical">
    <TextView
        android:id="@+id/header_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"
        android:textColor="@color/colorBlack"
        android:text="@string/app_name"/>
</LinearLayout>

 

item_layout.xml

Follow the same process like above and create a new layout file inside the layout folder. Name it item_layout.xml. Copy and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <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/direction_card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">
        <TextView
            android:id="@+id/item_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="24dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="16sp"
            android:gravity="center"
            android:text="@string/sample" />
        </android.support.v7.widget.CardView>
</LinearLayout>

 

ViewHolder Classes

Just like with the layout files, we are going to create two different ViewHolder classes which our adapter will make use of. This is the trick with adding header to android RecyclerView.

Let create our two ViewHolder classes now.

 

HeaderViewHolder.java

In the project package folder, create a new file and name it HeaderViewHolder.java. Open the file and add the code below to it.

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class HeaderViewHolder extends RecyclerView.ViewHolder{
    public TextView headerTitle;
    public HeaderViewHolder(View itemView) {
        super(itemView);
        headerTitle = (TextView)itemView.findViewById(R.id.header_id);
    }
}

 

ItemViewHolder.java

In the project package folder, create a new file and name it ItemViewHolder.java. Open the file and add the code below to it.

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ItemViewHolder extends RecyclerView.ViewHolder{
    public TextView itemContent;
    public ItemViewHolder(View itemView) {
        super(itemView);
        itemContent = (TextView)itemView.findViewById(R.id.item_content);
    }
}

 

ItemObject.java

We are going to wrap our data in an object so we need to create a new java file and we will name it ItemObject.java. Since it is an entity object it will contain only a constructor and get method.

Open the file and add the code below.

public class ItemObject {
    private String contents;
    public ItemObject(String contents) {
        this.contents = contents;
    }
    public String getContents() {
        return contents;
    }
}

 

MainActivity Class and Its Layout File

We have create more of the layout files and classes we will use in this application. Now we will focus on how to integrate and bring everything together to achieve the aim we had from the beginning.

We will first start with the main layout file.

 

Activity_main.xml

The activity_main.xml is the main layout and it is used to display the UI view of the MainActivity class.

It is a simple layout file that will contain a RecyclerView widget. Open the layout file and add the code below.

<?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"
    android:layout_margin="4dp"
    tools:context="com.inducesmile.androidrecyclerviewheader.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/add_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scrollbars="none"/>
</RelativeLayout>

 

MainActivity.java

The MainActivity class will obtain an instance of the RecyclerView widget. It will call its setLayoutManager() method and we will pass an instance of a LinearLayoutManager.

Depending on the number of sections you plan to have you have to create instance of the HeaderRecyclerViewSection. In this Adding Sections in Android RecyclerView with SectionedRecyclerViewAdapter Library tutorial, we will use three sections.

We will create three different instance of HeaderRecyclerViewSection and pass a title and item data source to each of them as shown.

HeaderRecyclerViewSection firstSection = new HeaderRecyclerViewSection("First Section", getDataSource());
HeaderRecyclerViewSection secondSection = new HeaderRecyclerViewSection("Second Section", getDataSource());
HeaderRecyclerViewSection thirdSection = new HeaderRecyclerViewSection("Third Section", getDataSource());

We will create an object of SectionedRecyclerViewAdapter class and pass all our HeaderRecyclerViewSection objects as parameter to addSection() method.

The section adapter object is used as a parameter for the setAdapter() method of the RecyclerView class.

Open the MainActivity class and add the code below.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView sectionHeader;
    private SectionedRecyclerViewAdapter sectionAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sectionHeader = (RecyclerView)findViewById(R.id.add_header);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
        sectionHeader.setLayoutManager(linearLayoutManager);
        sectionHeader.setHasFixedSize(true);
        HeaderRecyclerViewSection firstSection = new HeaderRecyclerViewSection("First Section", getDataSource());
        HeaderRecyclerViewSection secondSection = new HeaderRecyclerViewSection("Second Section", getDataSource());
        HeaderRecyclerViewSection thirdSection = new HeaderRecyclerViewSection("Third Section", getDataSource());
        sectionAdapter = new SectionedRecyclerViewAdapter();
        sectionAdapter.addSection(firstSection);
        sectionAdapter.addSection(secondSection);
        sectionAdapter.addSection(thirdSection);
        sectionHeader.setAdapter(sectionAdapter);
    }
    private List<ItemObject> getDataSource(){
        List<ItemObject> data = new ArrayList<ItemObject>();
        data.add(new ItemObject("This is the item content in the first position"));
        data.add(new ItemObject("This is the item content in the second position"));
        return data;
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.

3 Comments

Add a Comment