Android 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. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. RecyclerView decouples the positioning, animating items and various event handling into different classes.
This tutorial shows you, how to develop a RecyclerView application.

Step 1:
Create a new Android project "RecyclerView" with package name: "com.javahelps.recyclerview".


Step 2:
RecyclerView is part of the support library, so it has to be added to the build.gradle(Module:app).
Add the following dependency to build.gradle(Module:app) and sync the project with Gradle files.
compile 'com.android.support:recyclerview-v7:23.1.0'


Step 3:
Modify the activity_mani.xml by adding a RecyclerView as shown below.
<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />

After adding the RecyclerView, the activity_main.xml should look like this:
<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

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

Step 4:
Add a new layout file named layout_item.xml. Later this layout will be used to create the view of RecyclerView items.


Step 5:
Create two TextViews and a View inside the layout_item.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="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txtDirector"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="right"
        android:text="Director" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:background="#bfbdbd" />
</LinearLayout>
In this layout, the last View is used as a separator.

Step 6:
Create a new Java class Movie and modify it as shown below:
package com.javahelps.recyclerview;

public class Movie {
    private String name;
    private String director;

    public Movie(String name, String director) {
        this.name = name;
        this.director = director;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }
}
This class is used to represent some movies in this project.

Step 7:
Create another Java class MovieViewHolder, which must extends RecyclerView.ViewHolder class.
package com.javahelps.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MovieViewHolder extends RecyclerView.ViewHolder {
    // User interface components
    private TextView txtName;
    private TextView txtDirector;
    // Movie to be used by OnClickListener
    private Movie movie;

    public MovieViewHolder(View itemView) {
        super(itemView);
        // Find the user interface components
        this.txtName = (TextView) itemView.findViewById(R.id.txtName);
        this.txtDirector = (TextView) itemView.findViewById(R.id.txtDirector);

        // Set OnClickListener
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get the context
                Context context = v.getContext();
                // Show the name of the movie in a Toast
                Toast.makeText(context, movie.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setMovie(Movie movie) {
        // Assign the movie to the instance variable
        this.movie = movie;
        // Set the content to the view
        this.txtName.setText(movie.getName());
        this.txtDirector.setText(movie.getDirector());
    }
}
This class holds the view of an item and set event listener for item click events.

Step 8:
Create another class MovieAdapter which is a subclass of RecyclerView.Adapter class.
package com.javahelps.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

public class MovieAdapter extends RecyclerView.Adapter<MovieViewHolder> {
    // List of movies for this adapter
    private List<Movie> movies;

    public MovieAdapter(List<Movie> movies) {
        this.movies = movies;
    }

    /**
     * This method is called by LayoutManager to create a new method.
     */
    @Override
    public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Get the parent view's context
        Context context = parent.getContext();
        // Inflate the layout_item
        View view = LayoutInflater.from(context).inflate(R.layout.layout_item, parent, false);
        // Create a ViewHolder
        MovieViewHolder viewHolder = new MovieViewHolder(view);
        return viewHolder;
    }

    /**
     * This method is called by LayoutManager to bind the ViewHolder with required data.
     */
    @Override
    public void onBindViewHolder(MovieViewHolder holder, int position) {
        // Get the movie at the given position
        Movie movie = movies.get(position);
        // Set the movie to the ViewHolder
        holder.setMovie(movie);
    }

    @Override
    public int getItemCount() {
        // Return the size of the data
        return movies.size();
    }
}
This class wraps the entire data set and creates views for individual items.

Step 9:
Open the MainActivity.java and add the following instance variables and method.
// RecyclerView user interface component
private RecyclerView recyclerView;

// Adapter for the RecyclerView
private RecyclerView.Adapter<MovieViewHolder> adapter;

// LayoutManager for the RecyclerView
private RecyclerView.LayoutManager layoutManager;

/**
 * Create a List of Movies.
 */
private List<Movie> getMovies() {
    // Create a List of movies
    List<Movie> movies = new ArrayList<>();
    movies.add(new Movie("Star Wars", "J.J. Abrams"));
    movies.add(new Movie("The Martian", "Ridley Scott"));
    movies.add(new Movie("Crimson Peak", "Guillermo del Toro"));
    movies.add(new Movie("Pan", "Joe Wright"));
    movies.add(new Movie("Knock Knock", "Eli Roth"));
    movies.add(new Movie("Sicario", "Denis Villeneuve"));
    movies.add(new Movie("The Walk", "Robert Zemeckis"));
    movies.add(new Movie("Black Mass", "Scott Cooper"));
    movies.add(new Movie("Goosebumps", "Rob Letterman"));
    movies.add(new Movie("Dope", "Rick Famuyiwa"));

    return movies;
}
In this code, getMovies method create a list of movies and return it.

Step 10:
Modify the onCreate method as given below:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Find the UI components
    this.recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    // Arrange the items linearly
    this.layoutManager = new LinearLayoutManager(this);

    // Get the movies
    List<Movie> movies = getMovies();

    // Create the MovieAdapter
    this.adapter = new MovieAdapter(movies);

    // Set the LayoutManager
    this.recyclerView.setLayoutManager(layoutManager);

    // Set the Adapter
    this.recyclerView.setAdapter(adapter);
}
In this code, LinearLayout is used to provide a similar functionality ti ListView.

After the modification, the MainActivity.java should look like this:
package com.javahelps.recyclerview;

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;

public class MainActivity extends AppCompatActivity {
    // RecyclerView user interface component
    private RecyclerView recyclerView;

    // Adapter for the RecyclerView
    private RecyclerView.Adapter<MovieViewHolder> adapter;

    // LayoutManager for the RecyclerView
    private RecyclerView.LayoutManager layoutManager;


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

        // Find the UI components
        this.recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        // Arrange the items linearly
        this.layoutManager = new LinearLayoutManager(this);

        // Get the movies
        List<Movie> movies = getMovies();

        // Create the MovieAdapter
        this.adapter = new MovieAdapter(movies);

        // Set the LayoutManager
        this.recyclerView.setLayoutManager(layoutManager);

        // Set the Adapter
        this.recyclerView.setAdapter(adapter);
    }

    /**
     * Create a List of Movies.
     */
    private List<Movie> getMovies() {
        // Create a List of movies
        List<Movie> movies = new ArrayList<>();
        movies.add(new Movie("Star Wars", "J.J. Abrams"));
        movies.add(new Movie("The Martian", "Ridley Scott"));
        movies.add(new Movie("Crimson Peak", "Guillermo del Toro"));
        movies.add(new Movie("Pan", "Joe Wright"));
        movies.add(new Movie("Knock Knock", "Eli Roth"));
        movies.add(new Movie("Sicario", "Denis Villeneuve"));
        movies.add(new Movie("The Walk", "Robert Zemeckis"));
        movies.add(new Movie("Black Mass", "Scott Cooper"));
        movies.add(new Movie("Goosebumps", "Rob Letterman"));
        movies.add(new Movie("Dope", "Rick Famuyiwa"));

        return movies;
    }
}

Step 11:
Save all the changes and run the application.


Find the project @ Git Hub.
Previous
Next Post »

Contact Form

Name

Email *

Message *