Android RecyclerView Example

RecyclerView

The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.

Here I would demonstrate you a working example of RecyclerView, with some basic functionality. The RecyclerView we are going to design contains a list of books displaying the book Image, name, and author.

Download Github code from Here.

Creating New Project

1.  In Android Studio, go to File New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed.

2.  Open build.gradle and add recycler view dependency com.android.support:recyclerview-v7:26.1.0 and rebuild the project.

Build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //RecyclerView
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    
}

3. I have refracted activity_main.xml by the name activity_booklist.xml in which I have added one RecyclerView with the following basic properties.

activity_booklist.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.example.lenovo.recyclerview.activity.BookListActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

Writing the Adapter Class

After adding the RecyclerView widget, let’s start writing the adapter class to render the data. The RecyclerView adapter is same as ListView but the override methods are different.

4. Create a class named Book.java and declare bookName, authorName and ImageResource(for Image). Also add the getter/setter methods to each variable.

Book.java

package com.example.lenovo.recyclerview.model;

public class Book {
    String authorName;
    String bookName;
    int imageResource;

    public Book(String authorName, String bookName, int imageResource) {
        this.authorName = authorName;
        this.bookName = bookName;
        this.imageResource = imageResource;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getImageResource() {
        return imageResource;
    }

    public void setImageResource(int imageResource) {
        this.imageResource = imageResource;
    }
}

5. Create a layout XML named book_list_row.xml with the below code. This layout file shows a single row in recycler view by displaying book name, image, and author name.

book_list_row.xml

<?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:layout_margin="5dp"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img_book"
        android:layout_width="100dp"
        android:layout_height="200dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/book_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="true"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="22sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/author_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textStyle="bold" />
    </LinearLayout>
</LinearLayout>

6. Now create a class named BookAdapter.java and add the below code. Here onCreateViewHolder() method inflates book_list_row.xml. In onBindViewHolder() method the appropriate book data (authorName, book name, and book image) set to each row.

BookAdapter.java

package com.example.lenovo.recyclerview.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.lenovo.recyclerview.R;
import com.example.lenovo.recyclerview.model.Book;
import java.util.List;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.MyViewHolder> {

    private List<Book> bookList;

    public BookAdapter(List<Book> bookList) {
        this.bookList = bookList;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView authorName, bookName;
        public ImageView imageView;

        public MyViewHolder(View view) {
            super(view);
            authorName = (TextView) view.findViewById(R.id.author_name);
            bookName = (TextView) view.findViewById(R.id.book_name);
            imageView = (ImageView) view.findViewById(R.id.img_book);
        }

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_list_row, parent, false);
        return new MyViewHolder(itemView);

    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.authorName.setText(bookList.get(position).getAuthorName());
        holder.bookName.setText(bookList.get(position).getBookName());
        holder.imageView.setImageResource(bookList.get(position).getImageResource());

    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }
}

7. Open drawable folder under res directory and paste all the book photos which you have copied from somewhere else.

8. Now open BookListActivity.java refracted form of MainActivity.java and do the below changes. Here prepareMovieData() method adds sample data to list view.

BookListActivity.java

package com.example.lenovo.recyclerview.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.example.lenovo.recyclerview.R;
import com.example.lenovo.recyclerview.adapter.BookAdapter;
import com.example.lenovo.recyclerview.model.Book;

import java.util.ArrayList;
import java.util.List;

public class BookListActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private List<Book> bookList = new ArrayList<Book>();
    private BookAdapter mAdapter;

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        prepareBookData();

        mAdapter = new BookAdapter(bookList);
        //vertical RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        //provides basic animations on remove, add, and move events that happen to the items in a RecyclerView.
        //RecyclerView uses a DefaultItemAnimator by default.
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

    }

    //preparing bookList data
    private void prepareBookData() {
        Book book = new Book("Munshi Premchand", "Nirmala", R.drawable.nirmala);
        bookList.add(book);
        book = new Book("Harivansh Rai Bachchan", "Madhushala", R.drawable.madhushala2);
        bookList.add(book);
        book = new Book("Ramdhari Singh Dinkar", "Rashmirathi", R.drawable.rashmirathi);
        bookList.add(book);
        book = new Book("Dharamvir Bharti", "Gunahon Ka Devta", R.drawable.gunahokedevta2);
        bookList.add(book);
        book = new Book("Munshi Premchand", "Shatranj Ke Khiladi", R.drawable.shatranj2);
        bookList.add(book);
        book = new Book("Bhisham Sahni", "Tamas", R.drawable.tamas);
        bookList.add(book);
        book = new Book("Dharamvir Bharti", "Suraj Ka Satva Ghoda", R.drawable.suraj);
        bookList.add(book);
        book = new Book("Munshi Premchand", "Karmabhumi", R.drawable.karmabhumi);
        bookList.add(book);
        book = new Book("Kashinath Singh", "Kassi Ka Assi", R.drawable.kashi_ka_assi);
        bookList.add(book);
        book = new Book("Bhagwati Charan Verma", "Chitralekha", R.drawable.chitralekha);
        bookList.add(book);

    }
}

Now if you run the app you can see the book list will look like this:

Screenshot_1581062693

Adding RecyclerView Divider/Separator

9. You can add the divider line between rows by using DividerItemDecoration provided by the support library. Add item decoration on RecyclerView as shown below.

// adding inbuilt divider line
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
//setting Adapter
 recyclerView.setAdapter(mAdapter);

Now if you run the app, you should see a divider line separating each row.

Displaying Horizontal Scrolling RecyclerView

10. If you want to display the RecyclerView in Horizontal manner, you can do that just by changing a single line of code. All you have to do is provide direction to layout manager i.e LinearLayoutManager.HORIZONTAL as shown below.

//horizontal recyclerView
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

Complete Code

Below is the complete code of  BookListActivity.java.

BookListActivity.java

package com.example.lenovo.recyclerview.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.example.lenovo.recyclerview.R;
import com.example.lenovo.recyclerview.adapter.BookAdapter;
import com.example.lenovo.recyclerview.model.Book;

import java.util.ArrayList;
import java.util.List;

public class BookListActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private List<Book> bookList = new ArrayList<Book>();
    private BookAdapter mAdapter;

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        prepareBookData();

        mAdapter = new BookAdapter(bookList);
        //vertical RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        //horizontal RecyclerView
        //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

        //provides basic animations on remove, add, and move events that happen to the items in a RecyclerView.
        //RecyclerView uses a DefaultItemAnimator by default.
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //adding inbuilt divider line
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(mAdapter);

    }

    //preparing bookList data
    private void prepareBookData() {
        Book book = new Book("Munshi Premchand", "Nirmala", R.drawable.nirmala);
        bookList.add(book);
        book = new Book("Harivansh Rai Bachchan", "Madhushala", R.drawable.madhushala2);
        bookList.add(book);
        book = new Book("Ramdhari Singh Dinkar", "Rashmirathi", R.drawable.rashmirathi);
        bookList.add(book);
        book = new Book("Dharamvir Bharti", "Gunahon Ka Devta", R.drawable.gunahokedevta2);
        bookList.add(book);
        book = new Book("Munshi Premchand", "Shatranj Ke Khiladi", R.drawable.shatranj2);
        bookList.add(book);
        book = new Book("Bhisham Sahni", "Tamas", R.drawable.tamas);
        bookList.add(book);
        book = new Book("Dharamvir Bharti", "Suraj Ka Satva Ghoda", R.drawable.suraj);
        bookList.add(book);
        book = new Book("Munshi Premchand", "Karmabhumi", R.drawable.karmabhumi);
        bookList.add(book);
        book = new Book("Kashinath Singh", "Kassi Ka Assi", R.drawable.kashi_ka_assi);
        bookList.add(book);
        book = new Book("Bhagwati Charan Verma", "Chitralekha", R.drawable.chitralekha);
        bookList.add(book);

    }
}

Now if you run the app you can see the book list will look like this:

Leave a Reply