Android RecyclerView is more advanced version of ListView with improved performance and other benefits. Using RecyclerView and CardView together, both lists and grids can be created very easily. Here is the complete information about RecyclerView and other examples.

In this tutorial we are going to learn how to render a simple RecyclerView with a custom layout. We’ll also learn writing a adapter class, adding list divider and row click listener. The recycler view we are going to design contains list of movies displaying the title, genre and year of release.

android-working-with-recycler-view

Below is the RecyclerView widget with necessary attributes.

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

Before you start, make sure that you updated your Android Studio to latest version. Currently my Android Studio is updated to Android Studio 2.0 Preview 6.

1. 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:23.1.1 and rebuild the project.

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

3. With the latest version of build tools, Android Studio is creating two layout files for each activity. For main activity, it created activity_main.xml (contains CoordinatorLayout and AppBarLayout) and content_main.xml (for the actual content). Open content_main.xml and the recycler view widget.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity">

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

</RelativeLayout>

4. Open colors.xml located under res ⇒ values and add below colors.

<?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="year">#999999</color>
    <color name="title">#222222</color>
</resources>

2. 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.

5. Create a class named Movie.java and declare title, genre and year. Also add the getter/setter methods to each variable.

package info.androidhive.recyclerview;

public class Movie {
    private String title, genre, year;

    public Movie() {
    }

    public Movie(String title, String genre, String year) {
        this.title = title;
        this.genre = genre;
        this.year = year;
    }

    public String getTitle() {
        return title;
    }

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

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }
}

6. Create an layout xml named movie_list_row.xml with the below code. This layout file renders a single row in recycler view by displaying movie name, genre and year of release.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:textColor="@color/title"
        android:textSize="16dp"
        android:textStyle="bold"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/genre"
        android:layout_below="@id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/year"
        android:textColor="@color/year"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_height="wrap_content" />

</RelativeLayout>

7. Now create a class named MoviesAdapter.java and add the below code. Here onCreateViewHolder() method inflates movie_list_row.xml. In onBindViewHolder() method the appropriate movie data (title, genre and year) set to each row.

package info.androidhive.recyclerview;

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

import java.util.List;

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

    private List<Movie> moviesList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            genre = (TextView) view.findViewById(R.id.genre);
            year = (TextView) view.findViewById(R.id.year);
        }
    }


    public MoviesAdapter(List<Movie> moviesList) {
        this.moviesList = moviesList;
    }

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

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Movie movie = moviesList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
    }

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

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

package info.androidhive.recyclerview;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    private List<Movie> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        mAdapter = new MoviesAdapter(movieList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        prepareMovieData();
    }

    private void prepareMovieData() {
        Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015");
        movieList.add(movie);

        movie = new Movie("Inside Out", "Animation, Kids & Family", "2015");
        movieList.add(movie);

        movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
        movieList.add(movie);

        movie = new Movie("Shaun the Sheep", "Animation", "2015");
        movieList.add(movie);

        movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015");
        movieList.add(movie);

        movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015");
        movieList.add(movie);

        movie = new Movie("Up", "Animation", "2009");
        movieList.add(movie);

        movie = new Movie("Star Trek", "Science Fiction", "2009");
        movieList.add(movie);

        movie = new Movie("The LEGO Movie", "Animation", "2014");
        movieList.add(movie);

        movie = new Movie("Iron Man", "Action & Adventure", "2008");
        movieList.add(movie);

        movie = new Movie("Aliens", "Science Fiction", "1986");
        movieList.add(movie);

        movie = new Movie("Chicken Run", "Animation", "2000");
        movieList.add(movie);

        movie = new Movie("Back to the Future", "Science Fiction", "1985");
        movieList.add(movie);

        movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981");
        movieList.add(movie);

        movie = new Movie("Goldfinger", "Action & Adventure", "1965");
        movieList.add(movie);

        movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
        movieList.add(movie);

        mAdapter.notifyDataSetChanged();
    }
}

Now if you run the app, you can see the movies displayed in a list manner.

android-recycler-view-example

3. Adding RecyclerView Divider / Separator

RecyclerView doesn’t have any divider related parameters to display the divider. Instead you need to extend a class from ItemDecoration and use addItemDecoration() method to display the divider.

9. Create a class named DividerItemDecoration.java and paste the below code.

package info.androidhive.recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by Lincoln on 30/10/15.
 */
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

10. Open MainActivity.java and set the item decoration using addItemDecoration() method before setting the adapter.

recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

// set the adapter
recyclerView.setAdapter(mAdapter);

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

android-recycler-view-separator-divider

4. Adding RecyclerView Item Click Listener

RecyclerView doesn’t have OnItemClickListener method too to identify item click. You need to write your own class extending RecyclerView.OnItemTouchListener.

11. Create a class named RecyclerTouchListener.java and extend it from RecyclerView.OnItemTouchListener. You can notice that ClickListener interface also added here.

public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private MainActivity.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

Finally add the recycler view item click listener as mentioned below.

recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Movie movie = movieList.get(position);
                Toast.makeText(getApplicationContext(), movie.getTitle() + " is selected!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

Run the app and verify the item click. You should able to see a toast message upon clicking on a row. You can also notice that a background ripple effect when testing on lollipop device.

android-recycler-view-on-item-click-listener

Final Code

Below is the complete code of my MainActivity.java

package info.androidhive.recyclerview;

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

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

public class MainActivity extends AppCompatActivity {
    private List<Movie> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        mAdapter = new MoviesAdapter(movieList);

        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Movie movie = movieList.get(position);
                Toast.makeText(getApplicationContext(), movie.getTitle() + " is selected!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        prepareMovieData();
    }

    private void prepareMovieData() {
        Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015");
        movieList.add(movie);

        movie = new Movie("Inside Out", "Animation, Kids & Family", "2015");
        movieList.add(movie);

        movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
        movieList.add(movie);

        movie = new Movie("Shaun the Sheep", "Animation", "2015");
        movieList.add(movie);

        movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015");
        movieList.add(movie);

        movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015");
        movieList.add(movie);

        movie = new Movie("Up", "Animation", "2009");
        movieList.add(movie);

        movie = new Movie("Star Trek", "Science Fiction", "2009");
        movieList.add(movie);

        movie = new Movie("The LEGO Movie", "Animation", "2014");
        movieList.add(movie);

        movie = new Movie("Iron Man", "Action & Adventure", "2008");
        movieList.add(movie);

        movie = new Movie("Aliens", "Science Fiction", "1986");
        movieList.add(movie);

        movie = new Movie("Chicken Run", "Animation", "2000");
        movieList.add(movie);

        movie = new Movie("Back to the Future", "Science Fiction", "1985");
        movieList.add(movie);

        movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981");
        movieList.add(movie);

        movie = new Movie("Goldfinger", "Action & Adventure", "1965");
        movieList.add(movie);

        movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
        movieList.add(movie);

        mAdapter.notifyDataSetChanged();
    }

}

What’s next?

I hope this article gave you very good knowledge on basics of RecyclerView. The next step is to follow the below article that explains advanced RecyclerView that combines CardView and RecyclerView in a grid fashion.

Android working with Card View and Recycler View

android-integrating-cardview-and-recyclerview-music-app
Change Log

Updated On 3rd Sep 2016 (Content Update, Bug fixes)
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Kamran

    thx Ravi

  • David Maraba S

    Nice

  • علي

    link doesn’t open!!

    • Which link?

      • علي

        the download link
        it just download php file
        then when I open it again it doesn’t open

        • Please try in some other browser.

          • Uh Oh…

            Can’t download code as can’t login, and can’t login as annoying and pointless ‘social options’ just go round and round in circles, always returning to login page. To be honest, I don’t really understand why one would require such extensive personal details to allow a download of a simple page of code? Shame, would have liked to engage in this, but it’s just way too much agro. Thanks anyway.

          • I am spending hours / days of time to write a single article. All I am expecting is one single email id (which is of 2 min task for you).

            Why don’t you try logging with google or facebook?

  • Abdel

    Thanks man ..keep up the good work (Y)

  • Vishal

    You and your guides are simply awesome. Thanks for doing such nice works !!

  • Today morning i was thinking why there is no updates from you, and here you are with RecyclerView 🙂

  • ravin

    What if I have clickable item in each item of the list for example each item having a button so how do i get the onclick for each of them.

    • You can attach the button click listener in ViewHolder and use an interface to trigger the method in your activity.

  • Whenever i tried to use ‘RecyclerView’ over ‘ListView’, i got confused. and now this tutorial !..ahh, thank you so much Ravi, big help for me, you are awesome.!

  • newDevL

    Hello Ravi, Nice tutorial.
    But how can you implement swipe to dismiss an item ?
    thankss

  • Chirag thaker

    Hi, Nice Tutorial, one question

    Why we can not run this application in Android Lolipop emulator , why only
    “com.android.support:appcompat-v7:23.1.1”

    not working with 21.0

    • You can update the android tools in SDK manager. Its always good practice to update to latest version.

      • Chirag thaker

        Okay Thanks, Please Update tutorial with that add Recyclerview item with animation , like example comes in “API Demos” in AVD

  • Taimur Hassan

    Thank you ravi for this great explanation.
    One question…
    How can we set background to any item on touch?
    I mean when I touch an item it should display some background color like in a list view but I didn’t find any solution of that. thank you.

  • Srivatsa Ramesh

    Thankyou so much…
    How can i add 3 button below every List
    which will be like FB having like,comment and share

    • You have to add them in movie_list_row.xml layout.

  • Shubham Patwa

    i want to add list of cards with recycler view can u please help me out

    • Simple add the CardView to movie_list_row.xml

    • FaisalHyder

      there you go you have a CardView implemented, too:)

  • FaisalHyder

    Hi there buddy, i am following you since 2014 i started Android and your tutorials just remarkable..!!
    One thing can’t you make the Interface thingy in the Adapter class with
    class MyItemsHolder extends RecyclerView.ViewHolder implements View.OnClickListener{} will help in lessening the code of MainActivity..!
    Still , your hard work is quite beyond the words of appreciation. 🙂

  • Hardik Mehta

    hii ravi, i m facing one problem i am adding email id to the recyclerview (email id’s are supplied by users by clicking floating action button and enter it in ediitext) after some position say 10th when i scroll up it messed with some other position’s data here is the code: http://stackoverflow.com/questions/34767362/edittext-in-recylerview-start-lossing-data

  • Suraj mistry

    Hi.. Ravi you are doing great job thank you so much and now I have a doubt regarding back-end means which database to used developing app I search on internet but got confused which one to used and which would be better to used and learn ,the information which I got is, regarding Realm is a mobile database and a good substitute for SQLite (Android) & CoreData (IOS) and parse.com is also getting shutdown what would I like to suggest me which database to used any idea pls reply. thank you.

  • Suraj mistry

    Hi.. Ravi you are doing great job thank you so much and now I have a doubt regarding back-end means which database to used developing app I search on internet but got confused which one to used and which would be better to used and learn ,the information which I got is, regarding Realm is a mobile database and a good substitute for SQLite (Android) & CoreData (IOS) and parse.com is also getting shutdown what would I like to suggest me which database to used any idea pls reply. thank you.

  • Suraj mistry

    Hi.. Ravi you are doing great job thank you so much and now I have a doubt regarding back-end means which database to used developing app I search on internet but got confused which one to used and which would be better to used and learn ,the information which I got is, regarding Realm is a mobile database and a good substitute for SQLite (Android) & CoreData (IOS) and parse.com is also getting shutdown what would I like to suggest me which database to used any idea pls reply. thank you.

  • Arslanali

    The minimum version API using Recycler View?

    • harin kaklotar

      @wwwitairru:disqus you can use RecyclerView for Minimum SDK: API 8: Android 2.2 with support library.

      • Arslanali

        Thanks for the answer.
        There is no problem recreating elements as a customary ListView ?

      • Arslanali

        Thank you very much for your response

        • harin kaklotar

          your welcome 🙂

  • Jévan Weekes

    is it possible to add an image to this like in your “custom list adapter tutorial”? The images are hosted on a shopping site and I need my app to access them, I tried the custom list tutorial but kept getting debug errors so i’m hoping I can get it working this way

  • King Kazma

    Hi, thanks for the great tutorial. What if i want to load my data from database is there any any function as cursorAdaptor in recyclerview

  • Anubhav

    Animation is not showing when i touch any item.Please help me…

  • Clay24g

    Great material design tutorials. Keep them coming.

  • ilham fadhli

    What if i want to load my data from https (jsonobject) and want to show in recyclerview?

  • Umar

    Hey, please add a tutorial for handling multiple item selection using recycler view !

  • iJavaYou

    Hey, nice blog but I would like to add something.
    what do you mean with there is no “Click listener” for the RecyclerView?
    You made it way too complex. Here is my solution, saves your Listener implementation and all those dozens of lines of code.

    In your MyViewHolder class you are passing a View (the Card). Every View has an onClick listener already implemented.
    v.setOnClicklistener(new OnClickListener{

    });

  • Sharoon Amjid

    Hi firstly you are an amazing teacher. If a person like me understand it then I think anyone can understand it easily. THANK YOU
    I’v minor problem in my app, I’m making attendance app for my college project, So i’v recyclerview to show student list, and switch widget to update the last taken attendance. The problem is the some of the switch get’s on or off unexpectedly and update some of the attendance unexpectedly when I scroll up or down. I think it’s because of recycling but how to solve this issue.If the switch goes to “on” it update the student attendance to present and if “off” the attendance is marked absent. So it is not good if the switch goes on and off unexpectedly because it updates the attendance unintentionally.

  • Villa Nanda

    Hi Ravi, this is a great tutorial, but i found a little problem, you should change a layout_height of in movie_list_row.xml from match_parent to wrap_content.
    cause when I scrolled down, the row item become large.

    Thanks for your tutorial, Keep going

    • Oh okay. I’ll check it.

      Thanks.

      • I think the problem is with RecycleView bug. Use updated library.

        compile ‘com.android.support:recyclerview-v7:23.2.1’

        • Yeah, I’ll update.

          • Lijo Varghese

            Hi Ravi,
            Great Tutorial.
            But I’m facing a small issue even though I make “layout_height” as “wrap_content” the RecyclerView is coming small and I’m able to scroll all the list items with in that View only.
            Please help.

            View is something like this : https://dl.dropboxusercontent.com/s/5pc5was2bjxzrd9/1.PNG

        • Atul

          I am using v7:23.2.1 only. I don’t think its version issue. It should be ‘wrap_content’ and not ‘match_parent ‘.

    • Bruno Chichava

      Yess, I had the same problem, but after this change is working well

  • This devider didn’t work for me, but I found another simple one. https://gist.github.com/polbins/e37206fbc444207c0e92

  • Shujhal Singh

    during data from server when it refresh the same data show multiple time how to remove this

    • before fetching data from server ,check whether you are clearing the data or not means

      mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override
      public void onRefresh() {
      yourdataset.clear();
      //your data set means ,the bean object
      youradapter.notifyDataSetChanged();
      MY_SERVERDATA_PAGE_NUMBER = 1;
      fetchDataFromServer();
      mSwipeRefreshLayout.setRefreshing(false);
      }
      });

      • Shujhal Singh

        thanks sir

  • vikas kumar

    hi ravi can you detail here how to get onclicklistener for each item like a button in the row. how do i know if that button has been clicked, i have tried but gets clicked on whole row rather than single item in a row.thanks

    • You need to add click listener in ViewHolder method.

      Example:
      public class ViewHolder extends RecyclerView.ViewHolder {

      Button button;

      public ViewHolder(View view) {
      super(view);
      button = (Button) itemView.findViewById(R.id.button);

      button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      }
      });

      }
      }

  • ARASHI Funsho

    Hi Ravi, I am having trouble adapting this code for use with fragments. On load of the fragment, the app crashes with a nullPointer exception on a line similar to this:

    recyclerView.setAdapter(mAdapter);

    Please help!

    Thanks

    • Dimas syuhada

      try to put the adapter in the onCreateView on your fragment.
      it should look like this

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.fragment_one, container, false);
      recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
      mAdapter = new yourAdapter(yourList);
      recyclerView.setAdapter(mAdapter);

      or you should look at this. it might be solve your problem. cause i’ve got same problem and solved by this.
      https://developer.android.com/intl/es/samples/RecyclerView/src/com.example.android.recyclerview/RecyclerViewFragment.html

      • ARASHI Funsho

        Thanks Dimas, will try what you suggested and revert.

      • ARASHI Funsho

        It was an issue with ButterKnife that sparked the error. I was only able to fix it last week monday…. Thanks anyway Dimas

    • When the fragment is launched, lot of things will be null. You need to write an interface in fragment and call it at the end of onCreateView() method notifying that fragment is fully launched.

      • ARASHI Funsho

        Okay, but how do i go about doing that?

      • ARASHI Funsho

        It was an issue with ButterKnife that sparked the error. I was only able to fix it last week monday…. Thanks anyway

  • Jovie Brett Bardoles

    Thanks alot for the very well made tutorials man!

    • You are welcome 🙂

      • Jovie Brett Bardoles

        Do you have a sample app or code in your github where there’s also an image on the listview in recyclerview? If not, can you help me how to declare an image on Movies adapter?
        I wish your tutorial have that also hehe.

  • Atul

    In the movie_list_row.xml are we sure android:layout_height=”match_parent” ? This creates row full of screen height. I think it should be android:layout_height=”wrap_content”

    • hitesh810

      hmmm i have also face this problem use layout_height and width of Parent layout wrap_content

    • Lewis

      yeahh that’s right

  • Atul

    In RecyclerTouchListener, please note getChildPosition(view) is deprecated method. We can use getChildLayoutPosition(view) instead.

  • Vikram maxim

    hi ravi how to create horizontal recycler view?pls help me

    • Rajkumar prajapati

      say me what to do?

    • hitesh810

      Use this-

      LinearLayoutManager layoutManager

      = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

      RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);

      myList.setLayoutManager(layoutManager);

      • Rajkumar prajapati

        i have 4 option in my application how to know wich is click?

        • hitesh810

          add toast message inside onclick listner metod

          • Sachin Rajput

            hey man i made an example
            where recycler view is having some textview or edit text with one button
            on clicking of that button update that text value and then after scrolling , the
            value is misplacing can u help

  • Umut Dönmez

    Ty for this code and tutorial . I wanna modify your code on my project. Ty again 😀

  • richest man alive

    Hi rav, thanks for your tutorial. I am trying to update specific parameters on my cardview at regular intervals. i’m stuck, pls i need your help

  • tuan phuong tran

    Hi buddy! Thank you for your awesome tutorial. I spent a few hours to play around with your code and I recognized that it needs some modification at movie_list_row. Instead of saying layout_height=”match_parent”, it should be layout_height=”wrap_content”. This ensures that your code will work like a charm. Thanks anyway!

    • Vijender R

      That’s a good catch Tuan. Or else each row fills up almost the entire screen on scrolling. Thanks for updating.

  • ARASHI Funsho

    Hi Ravi, I am looking for a post in which you showed how to create JSON using PHP. You talked about it in the concluding part of a post but i cannot find that post.

    Please reply asap. Thanks

  • Aiswarya olakkal

    thank you Ravi, It’s great work

    • You are welcome 🙂

      • Nitin Gandge

        I am getting error on this line..
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        In which file I have to add ToolBar?

        • Have you added toolbar in your layout file?

          • Nitin Gandge

            In which layout file?

  • Prajwal achar

    Awesome tutorial ravi. Have been following your tutorials from a long time. I have one issue with above tutorial. The onClick method is giving wrong row names. Initially when app is opened for first time it gives proper names on clicking the rows. Once scrolled, it starts giving wrong row names.I think the problem is with getting the position of the item. I am not able to find the exact point that is causing this issue.

    • Have you run the code downloaded from this article and check.

      • Prajwal achar

        Hey I got to know the issue now. I was using a different way to set the title, year and genre views in MoviesAdapter class which was causing the bug. I had actually made those three view variables global to the MoviesAdapter class and not to MyViewHolder class. I replaced the code as you’ve explained in the tutorial and now its working fine 🙂 But why is it so that we should not make those view variables global to MoviesAdapter class? Any explanation would be greatly appreciated. BTW thanks a LOT for this wonderful tutorial.

  • taufiq rachman

    awesome tutorial. how to create menu on the onLongClick?

  • tarun jain

    how can i add image in my Recycler View???

    • gorrox23

      Inflate RecyclerView element with a layout that contains an ImageView, then set the image resource to the image you want

  • |/|@¥@|||€

    hello sir, first of all thank u for making my work so easy and providing good turorials from which i learnt a lot. I have one issue in making different types of cardview in recycler view. I want two cardview of one type in two rows and one cardview of other type in 3rd 4th 5th row . so how is it possible to make . please suggest me sir..

    • Hi

      You need to use getItemViewType() to return different values for your 3,4,5 rows using the position param. Do the following

      declare two variables at the top
      int VIEW_CARD1 = 100;
      int VIEW_CARD2 = 200; // for 3,4,5 rows

      int getItemViewType() method

      @Override

      public int getItemViewType(int position) {

      if(position == 3 || position == 4 || position == 5)

      return VIEW_CARD2;

      else

      return VIEW_CARD1;
      }

      Now inflate two different layouts depending on viewType in onCreateViewHolder() method

      @Override

      public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

      View itemView;

      if(viewType == VIEW_CARD2){

      // inflate the layout of 3,4,5 the rows

      itemView = LayoutInflater.from(parent.getContext())

      .inflate(R.layout.layout_of_card1, parent, false);

      }else{

      // remaining all rows

      itemView = LayoutInflater.from(parent.getContext())

      .inflate(R.layout. layout_of_card2, parent, false);

      }

      return new MyViewHolder(itemView);

      }

      Tell me if you still have doubts

      • |/|@¥@|||€

        Thanks for the reply sir, I already done with this way but not getting desired output so i use this way

        public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

        public static final int VIEWTYPE_GRID_ITEM = 1;

        public static final int VIEWTYPE_LIST_ITEM = 2;

        private Context context;

        private RecyclerView mRecyclerView;

        private CustomAdapter mAdapter;

        private GridLayoutManager mLayoutManager;

        private String[] mDataset = {“SCAN TICKETS”, “ATTENDEE”, “BOOKING”, “TICKETS”, “Half Life 3 announced”, “Half Life 3 announced”, “Half Life 3 announced”};

        private int mDatasetTypes[] = {VIEWTYPE_GRID_ITEM, VIEWTYPE_GRID_ITEM, VIEWTYPE_GRID_ITEM, VIEWTYPE_GRID_ITEM, VIEWTYPE_LIST_ITEM, VIEWTYPE_LIST_ITEM, VIEWTYPE_LIST_ITEM}; //view types

        @Override

        protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_dashboard);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        context = this;

        init();

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

        mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);

        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

        @Override

        public int getSpanSize(int position) {

        return mAdapter.getItemViewType(position) == VIEWTYPE_GRID_ITEM ? 1 : 2;

        }

        });

        mRecyclerView.setLayoutManager(mLayoutManager);

        //Adapter is created in the last step

        mAdapter = new CustomAdapter(mDataset, mDatasetTypes, init());

        mRecyclerView.setAdapter(mAdapter);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(

        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawer.setDrawerListener(toggle);

        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(this);

        }

        private ArrayList init() {

        ArrayList arrayList = new ArrayList();

        arrayList.add(new GridView(R.drawable.scan_tickets_card_icon, “SCAN TICKETS”, Color.parseColor(“#3DA3E5”)));

        arrayList.add(new GridView(R.drawable.attendee_card_icon, “ATTENDEE”, Color.parseColor(“#DC5387”)));

        arrayList.add(new GridView(R.drawable.booking_card_icon, “BOOKING”, Color.parseColor(“#109F47”)));

        arrayList.add(new GridView(R.drawable.tickets_card_icon, “SCAN TICKETS”, Color.parseColor(“#3DA3E5”)));

        return arrayList;

        }

        @Override

        public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

        // Respond to the action bar’s Up/Home button

        case android.R.id.home:

        // NavUtils.navigateUpFromSameTask(this);

        finish();

        return true;

        }

        return super.onOptionsItemSelected(item);

        }

        @Override

        public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();

        Intent i = null;

        if (id == R.id.nav_scan_events) {

        // Handle the action

        i = new Intent(context, EventDetails.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_attendee) {

        i = new Intent(context, Attendee.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_bookings) {

        i = new Intent(context, Bookings.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_tickets) {

        i = new Intent(context, Tickets.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_reports) {

        i = new Intent(context, Reports.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_scanlog) {

        i = new Intent(context, ScanLog.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_ticketLog) {

        i = new Intent(context, TicketLog.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_whatsNew) {

        i = new Intent(context, WhatsNew.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_group_scan) {

        i = new Intent(context, GroupScan.class);

        startActivity(i);

        } else if (id == R.id.nav_scan_ticket_scan) {

        i = new Intent(context, ScanActivity.class);

        startActivity(i);

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        drawer.closeDrawer(GravityCompat.START);

        return true;

        }

        public class CustomAdapter extends RecyclerView.Adapter {

        private static final String TAG = “CustomAdapter”;

        private String[] mDataSet;

        private int[] mDataSetTypes;

        private ArrayList arrayList;

        public static final int VIEWTYPE_GRID_ITEM = 1;

        public static final int VIEWTYPE_LIST_ITEM = 2;

        public class ViewHolder extends RecyclerView.ViewHolder {

        public ViewHolder(View v) {

        super(v);

        }

        }

        public class SquareViewHolder extends ViewHolder {

        TextView temp;

        ImageView ivImage;

        CardView cardView;

        public SquareViewHolder(View v) {

        super(v);

        this.temp = (TextView) v.findViewById(R.id.temp);

        this.ivImage = (ImageView) v.findViewById(R.id.ivIcon);

        this.cardView = (CardView) v.findViewById(R.id.cardview);

        }

        }

        public class RectangleViewHolder extends ViewHolder {

        TextView headline, score;

        ListView listview;

        public RectangleViewHolder(View v) {

        super(v);

        this.headline = (TextView) v.findViewById(R.id.tv1);

        this.score = (TextView) v.findViewById(R.id.temp);

        // listview = (ListView) v.findViewById(R.id.listview);

        }

        }

        public CustomAdapter(String[] dataSet, int[] dataSetTypes, ArrayList arrayList) {

        mDataSet = dataSet;

        mDataSetTypes = dataSetTypes;

        this.arrayList = arrayList;

        }

        @Override

        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View v;

        if (viewType == VIEWTYPE_GRID_ITEM) {

        v = LayoutInflater.from(viewGroup.getContext())

        .inflate(R.layout.cardview_dashboard_square, viewGroup, false);

        return new SquareViewHolder(v);

        } else {

        v = LayoutInflater.from(viewGroup.getContext())

        .inflate(R.layout.cardview_dashboard_rectangle, viewGroup, false);

        return new RectangleViewHolder(v);

        }

        }

        @Override

        public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        if (viewHolder.getItemViewType() == VIEWTYPE_GRID_ITEM) {

        SquareViewHolder holder = (SquareViewHolder) viewHolder;

        holder.temp.setText(arrayList.get(position).getHeading());

        holder.ivImage.setImageResource(arrayList.get(position).getIcon());

        holder.cardView.setCardBackgroundColor(arrayList.get(position).getColor());

        } else {

        RectangleViewHolder holder = (RectangleViewHolder) viewHolder;

        holder.headline.setText(mDataSet[position]);

        }

        }

        @Override

        public int getItemCount() {

        return mDataSet.length;

        }

        @Override

        public int getItemViewType(int position) {

        return mDataSetTypes[position];

        }

        }

        }

        please add this code so viewers can also use this code.

      • |/|@¥@|||€

        hello sir i have doubt to show recyclerview in fragment means i want to show data on each tab click for which i am using view pager but on click working fine but on swipping tabs application crashed with below message

        java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 0(offset:0).state:17

        Please help me out i am struggling from last 1 week

        public class MenuData extends Fragment {

        /**

        * The fragment argument representing the section number for this

        * fragment.

        */

        private RecyclerView recyclerView;

        private LinearLayoutManager mLayoutManager;

        private GridAdapter mGridAdapter;

        public MenuData() {

        }

        @Override

        public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);

        // outState.putSparseParcelableArray(keys.KEY_MENU_DATA, arMenuDataList.t);

        }

        @Override

        public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        }

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container,

        Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_menu_items, container, false);

        recyclerView = (RecyclerView) rootView.findViewById(R.id.menu_recycler_view);

        mLayoutManager = new LinearLayoutManager(getActivity());

        recyclerView.setLayoutManager(mLayoutManager);

        return rootView;

        }

        @Override

        public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {

        Bundle bundle = this.getArguments();

        String menu_name = bundle.getString(“name”);

        FetchMenuDetails fetchMenuDetails = new FetchMenuDetails(menu_name);

        setRetainInstance(true);

        // launch your AsyncTask here, if the task has not been executed yet

        if (Constants.isNetConnected(getActivity())) {

        if (fetchMenuDetails.getStatus() != AsyncTask.Status.RUNNING) {

        fetchMenuDetails.execute();

        }

        } else {

        showDialog();

        }

        }

        }

        private class FetchMenuDetails extends AsyncTask {

        String menu_name = “”;

        String res = “”;

        FetchMenuDetails(String name) {

        menu_name = name;

        }

        @Override

        protected String doInBackground(Void… voids) {

        // Boolean server_response = false;

        Map param = new HashMap();

        String requestURL = Constants.SERVER_URL;

        param.put(“type”, menu_name);

        arMenuDataList = new ArrayList();

        try {

        WebRequest.sendPostRequest(requestURL, param);

        String[] response = WebRequest.readMultipleLinesRespone();

        for (String line : response) {

        System.out.println(line);

        res = line;

        }

        } catch (Exception e) {

        Log.v(“exception”, e.getMessage());

        } finally {

        // progressDialog.dismiss();

        WebRequest.disconnect();

        }

        return res;

        }

        @Override

        protected void onPostExecute(final String success) {

        // check login is success or not

        Boolean server_response = false;

        try {

        JSONObject jsonObject = new JSONObject(success);

        JSONArray jsonArray = jsonObject.optJSONArray(“key”);

        int length = jsonArray.length();

        if (length != 0) {

        for (int i = 0; i < length; i++) {

        MenuDataList menuData = new MenuDataList();

        JSONObject jsonObject1 = jsonArray.optJSONObject(i);

        menu_name = jsonObject1.optString(keys.KEY_MENU_NAME);

        type = jsonObject1.optString(keys.KEY_MENU_TYPE);

        half_rate = jsonObject1.optString(keys.KEY_MENU_HALF_RATE);

        full_rate = jsonObject1.optString(keys.KEY_MENU_FULL_RATE);

        menuData.setName(menu_name);

        menuData.setType(type);

        menuData.setFull_rate(full_rate);

        menuData.setHalf_rate(half_rate);

        menuData.setHalf_count(0);

        menuData.setFull_count(0);

        arMenuDataList.add(menuData);

        }

        server_response = true;

        } else {

        server_response = false;

        }

        if (server_response) {

        mGridAdapter = new GridAdapter();

        recyclerView.setAdapter(mGridAdapter);

        mGridAdapter.setMenuList(arMenuDataList);

        mGridAdapter.notifyDataSetChanged();

        } else {

        }

        } catch (Exception e) {

        e.printStackTrace();

        }

        }

        @Override

        protected void onCancelled() {

        WebRequest.disconnect();

        }

        }

        }

    • int view_type1=1;
      int viw_type2=2;

      public int getItemViewType(int position) {
      if (yourBeanObject.get(position).yourViewType == view_type1) {
      //do something
      }else{
      //do something
      }

      • |/|@¥@|||€

        ohk thanks sir 🙂

  • Deep Gosalia

    Hello sir, I am from first year engg. I know some basics of JAVA and recently started learning Android.
    Sir, how do i learn meaning and structure of every code line in Android Programming ??
    Please help me sir. (I would like to know how u learnt i.e. any books,videos,…..etc)

  • Troy Chuinard

    Ravi – I am getting a NullPointer here. For some reason the RecyclerView is not recognizing the XML in my individual_view item

    public class ViewHolder extends RecyclerView.ViewHolder {

    // each data item is just a string in this case

    protected ImageView userAvatar;

    protected TextView userID;

    protected TextView userComment;

    public ViewHolder(View v) {

    super(v);

    userAvatar = (ImageView) findViewById(R.id.profile_image);

    userID = (TextView) findViewById(R.id.user_ID);

    userComment = (TextView) findViewById(R.id.user_comment_textview);

    }

    }

    // Provide a suitable constructor (depends on the kind of dataset)

    public MyAdapter(ArrayList myDataset) {

    mDataSet = myDataset;

    }

    // Create new views (invoked by the layout manager)

    @Override

    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,

    int viewType) {

    // create a new view

    View v = LayoutInflater.from(parent.getContext())

    .inflate(R.layout.individual_comment, parent, false);

    // set the view’s size, margins, paddings and layout parameters

    return new ViewHolder(v);

    }

    The nullPointer is occurring here:

    @Override

    public void onBindViewHolder(ViewHolder holder, int position) {

    Comments comment = mDataSet.get(position);

    holder.userComment.setText(comment.getUserComment());

    //

    //// holder.userComment.setText(mDataSet.get(position).getUserComment());

    // String x = mDataSet.get(position).getUserComment();

    // Log.v(“ON_BIND_VIEW”, “THE STRING IS ” + x);

    //// Log.v(“THE_POSITION”, “THE POSITION IS ” + position);

    }

    • Unil Gandhi

      Hi Troy,
      In your viewholder constructor, use :

      this.userAvatar = (ImageView) v.findViewById(R.id.profile_image);
      this.userID = (TextView) v.findViewById(R.id.user_ID);

  • Salman Saleem

    My android Studio does’nt simport RecyclerView what should i do ??

  • Manik

    Thanks…

  • Ankit Kumar

    Thank you Ravi, It was a simple and nice tutorial. But I am getting 1 problem. As soon as I scroll down the space between the movies increases and when I rotate the phone screen it gets back to original type but again after scrolling space increases.

    • Shubham Yadav

      wrap_content the height of the row_list layout will solve your problem

  • Er Pratik Chatterjee

    Hi,

    I have a recycler view with RecyclerView.OnItemTouchListener.
    items are getting clicked properly but i have button inside that item of recyclerview which is not getting clicked.tried focus afterdescendents too.

    need click on item as well as button inside that item both having different implementation-like when user clicks the item product details opens and when button is clicked product is added to cart.

    Thanks in adv

  • thank u very much 🙂

  • Manish Shakya

    Hello sir can you please help me,i want to run this Example in android kitkat 4.0 version is that possible ?

  • vinod

    sir, how can implement add to cart using recyclerview and cardview!!!!!!!!!!!!

  • Vishnu Mohan

    Nice tutorial Ravi… All your blogs are extremely helpful… Keep up the good work…

  • Kanwar preet

    // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    // setSupportActionBar(toolbar);

    getting error here not able to find toolbar

    • gorrox23

      Make sure you defined a Toolbar element in your Activity layout.
      If you want a Material Design look on your app, you need to set your theme to a NoActionBar style, and then implement a Toolbar instead

  • subm

    Sir, I have followed most of the steps you made.
    But my recycler view looks funny, each item takes a whole screen to scroll.
    Do you have any idea what’s wrong about it??

    Edit: Solved:D What if I want to intent some activities?

    • Kanwar preet

      same with me also

      • subm

        Does your items take a whole screen??
        You should change the layout height to wrap content in row.xml

    • Shubham Yadav

      can you share the solved method as im having the same issues.

      • subm

        The author made a small error in he code above.
        movie_list_row.xml>relativelayout>layoutheight>wrapcontent

  • vinod

    sir, how can we send selected items in recyclerview to pass other recylcerview in another activity!!!!!!

  • Hector Orozco

    Great job, but I have a problem. My app starts with a menu screen, then the user selects a module where the list is loaded, I modified your code to load data from a remote database, but when I enter the module the list is supposed to be loaded, the list is empty, showing blank space I need to exit to the previous screen and then re-enter the list module, only then the list shows the data. but the idea is to load data at the first attempt. I don’t know where is the problem maybe you could help me.

  • Aldy Putra W

    how to addd image in every item?

    • Tarek Zoubi

      u need to add the image in the recycle_view xml

  • Venky rockz

    Hello,
    I have an issue with my image listview as all the images showning in horizontal and i need to change them in vertical listview order so could anyone please help me of this??

    • Can u give any screenshot of existing output?

      • Venky rockz

        Thanks Ravi Tamada for quick respond . I solved the problem by changing in Layout as VERTICAL.

  • Mdu Dube

    How can I do this with a tabbed activity?

    • gorrox23

      You will have to use an activity that contains a ‘TabLayout’ and ‘ViewPager’ (to enable swiping between tabs as well) , and then a container below them in which you will inflate a fragment with the layout corresponding to to selected tab.

      You’ll also have to implement your own on-click listeners for the tabs themselves if I remember correctly.
      Here’s the guides I used (Also by Ravi)
      http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

  • Tarek Zoubi

    Hi Ravi thanks for your awesome tutorial
    i have an issue with the divider/seperator it works perfectly on first activity
    but i have two other activitys and the app crashes when i try to open them and the logcat refrences to this line

    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

    it says java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.widget.RecyclerView.addItemDecoration(android.support.v7.widget.RecyclerView$ItemDecoration)’ on a null object reference

    please help me

  • Vishal Mahajan

    when i was copy same code in sliding tab then it show null point exception error
    can anybody help me

  • Vishal Mahajan

    i think its due to fragment
    what can i do for fragment

  • Vishal Mahajan

    And yes Awesome tutorial ravi

  • Deepmala Singh

    thanks for your tutorial

  • Yonatan Eilat

    Amazing tutorial!
    thanks!!

  • Freddie Shalom Mukendi

    Hi Ravi can you please make a video where we can get the values in a RecyclerView. example get all the product information at a specific position when clicked. I have not seen a tutorial covering this on Youtube as yet. Everyone just leaves it at Toast showing position 0 etc…

    • Yes, using the position you can get the clicked production information. In this article, List movieList is used to display the list data. So using the position you can get the selected movie as Movie movie = movieList.get(position); By the way, this is already covered in this article.

      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
      @Override
      public void onClick(View view, int position) {
      Movie movie = movieList.get(position);
      Toast.makeText(getApplicationContext(), movie.getTitle() + ” is selected!”, Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onLongClick(View view, int position) {

      }
      }));

  • Bastobsongkhya Real

    I can’t find content_main.xml.My build version is “24.0.1”.help plz……

    • You can create a new file with that name. Check 3rd point.

  • Rey

    Hello Mr. Ravi,

    Thanks for this tutorial, but I am having some problems with the RecyclerView. I want to put this into a Fragment, everytime I scroll the items are expanding.

    This is the code.

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_favorites, container, false);

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
    mAdapter = new MoviesAdapter(movieList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);

    prepareMovieData();
    return view;

    }

    Please help. Thank you.

  • $|R_MYK3

    RAVI thanks for the Tutorial but i really have two request how can i make it fetch from mysql or json and two how can i make it when click it will display the activity selected in a new page with full detail like example

    when i click on any of the option it will open in as a new activity with the selected activity in it with more details like description, topic or title and also image if possible and a drop down swipe to refresh or pull to refresh

    thanks great app

      • $|R_MYK3

        thanks have looked @ the two tutorial they are great nice and well explained but the problem is i do not know how to merge the two program / tutorial to this one. and dont even know my way around Android studio thats i love this tutorial http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/ because its made under eclipse and easy to understand i kinda added this code to “facebook-like-custom-listview-feed-using-volley”

        public class Info extends Activity implements OnRefreshListener {

        @SuppressLint(“NewApi”)
        // Now find the PullToRefreshLayout and set it up
        mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
        ActionBarPullToRefresh.from(this)
        .allChildrenArePullable()
        .listener(this)
        .setup(mPullToRefreshLayout);

        the problem now is what to put in

        @Override
        public void onRefreshStarted(View view) {
        // TODO Auto-generated method stub

        }

        this is the full index.java or MainActivity.java

        package com.eliteinfo4all.base;

        import java.io.UnsupportedEncodingException;
        import java.util.ArrayList;
        import java.util.List;

        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;

        import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
        import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
        import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;

        import android.annotation.SuppressLint;
        import android.app.Activity;
        import android.content.Intent;
        import android.graphics.Color;
        import android.graphics.drawable.ColorDrawable;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.View;
        import android.widget.Button;
        import android.widget.ListView;

        import com.android.volley.Cache;
        import com.android.volley.Cache.Entry;
        import com.android.volley.Request.Method;
        import com.android.volley.Response;
        import com.android.volley.VolleyError;
        import com.android.volley.VolleyLog;
        import com.android.volley.toolbox.JsonObjectRequest;
        import com.eliteinfo4all.base.adapter.FeedListAdapter;
        import com.eliteinfo4all.base.app.AppController;
        import com.eliteinfo4all.base.data.FeedItem;

        public class Info extends Activity implements OnRefreshListener {
        private static final String TAG = Info.class.getSimpleName();
        private PullToRefreshLayout mPullToRefreshLayout;
        private ListView listView;
        private FeedListAdapter listAdapter;
        private List feedItems;
        private String URL_FEED = “http://192.168.211.1/android/info/index.php”;
        private Button btnLinkToMain;

        @SuppressLint(“NewApi”)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        btnLinkToMain = (Button) findViewById(R.id.backbtn);
        // Link to Login Screen
        btnLinkToMain.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
        Intent i = new Intent(getApplicationContext(),
        MainActivity.class);
        startActivity(i);
        finish();
        }
        });

        // Now find the PullToRefreshLayout and set it up
        mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
        ActionBarPullToRefresh.from(this)
        .allChildrenArePullable()
        .listener(this)
        .setup(mPullToRefreshLayout);

        // These two lines not needed,
        // just to get the look of facebook (changing background color & hiding the icon)
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(“#3b5998”)));
        getActionBar().setIcon(
        new ColorDrawable(getResources().getColor(android.R.color.transparent)));

        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_FEED);
        if (entry != null) {
        // fetch the data from cache
        try {
        String data = new String(entry.data, “UTF-8”);
        try {
        parseJsonFeed(new JSONObject(data));
        } catch (JSONException e) {
        e.printStackTrace();
        }
        } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        }

        } else {

        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
        URL_FEED, null, new Response.Listener() {

        @Override
        public void onResponse(JSONObject response) {
        VolleyLog.d(TAG, “Response: ” + response.toString());
        if (response != null) {
        parseJsonFeed(response);
        }
        }
        }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
        VolleyLog.d(TAG, “Error: ” + error.getMessage());
        }
        });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
        }

        }

        /**
        * Parsing json reponse and passing the data to feed view list adapter
        * */
        private void parseJsonFeed(JSONObject response) {
        try {
        JSONArray feedArray = response.getJSONArray(“feed”);

        for (int i = 0; i < feedArray.length(); i++) {
        JSONObject feedObj = (JSONObject) feedArray.get(i);

        FeedItem item = new FeedItem();
        item.setId(feedObj.getInt("id"));
        item.setName(feedObj.getString("name"));

        // Image might be null sometimes
        String image = feedObj.isNull("image") ? null : feedObj
        .getString("image");
        item.setImge(image);
        item.setStatus(feedObj.getString("status"));
        item.setProfilePic(feedObj.getString("profilePic"));
        item.setTimeStamp(feedObj.getString("timeStamp"));

        // url might be null sometimes
        String feedUrl = feedObj.isNull("url") ? null : feedObj
        .getString("url");
        item.setUrl(feedUrl);

        feedItems.add(item);
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
        e.printStackTrace();
        }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
        }

        @Override
        public void onRefreshStarted(View view) {
        // TODO Auto-generated method stub

        }

        }

  • Piero Mollica

    Hi Ravi. Thanks for this tutorial. it is very helpful. I have a problem with my application. I have a List that i want to fill dynamically from a database. I’m using an IntentService to send the request to the Database. So from this service i’m sending to my receiver an ArrayList . Now i’m sure this arrays is not empty. But i don’t know how to show this list in my activity. i followed you example to create a list using recyclerview etc… I added to my activity a receiver wich extends Broadcast receiver, but nothing… I help you can help me

  • Vishal Mahajan

    Ravi when i was click on download option then i subscribe with my gmailid and it never sent me no verify email so how can i download this or other code from android hive plz help me..

    • Try using gmail, facebook or other options on right side.

  • Vishal Mahajan
  • Abdul Rahman Majeed

    I am trying to use onScrollChange but this is for Marshmellow , how can i use to support older versions too ??

  • Nazrul Amin

    Hi Ravi, how to make this example to show as a Swipable Listview?

  • Luran Mahamin

    Hi Ravi, I’m am trying to this on my end however everytime I scroll down or scroll back on the list it gets messed up. It expands the whole screen for each item. Im using same xml values. How can I fix this?

    • Use wrap_content for the list view layout instead of match_parent and check.

  • Shreyansh Sharma

    Hi Ravi,Thanks for the amazing tutorial above.I have executed and things are working fine except this one thing inside the Recyclerview i.e. I have 20 cards involving a question and a rating bar to answer,the problem being the duplication of data in the views while scrolling. eg. I fill up the third question,the same rating is achieved on every fifth view from then.I dont get the problem ,Can u help?

    • Hi Sharma

      You need to use if else while rendering data to avoid duplicate rows. Give me screenshot of duplicate rows, I can give you solution.

      • Shreyansh Sharma

        Please find attached the dropbox link to the image containing the duplication of data.(I was unable to comment picture so i added this link)
        I tap on three grading point on first three questions and same thing is repeated automatically on 5,6,7 ; 10,11,12 ; 15,16,17 th view itself.
        https://www.dropbox.com/s/6ggzmjw9t1ci488/duplication%20of%20data.png?dl=0

        • Can u post your adapter class code too?

          • Shreyansh Sharma

            Hi Ravi,I am glad to have your assistance however if you could tell me your email id, I can send you the adapter class file as well as viewholder file attached through it.The code is large and somehow its not getting attached here

          • You can use PasteBin to upload the code.

  • Dammy

    I think there is a little modification in the “onInterceptTouchEvent” method overriden from the “RecyclerView.OnItemTouchListener” interface.

    The onClick operation is likely to respond twice when the Recycler list is being clicked (because it returns false), hence, modify your method to this:

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
    clickListener.onClick(child, rv.getChildPosition(child));
    return true; //add this expression in order to avoid double execution of this operation.
    }
    return false;
    }

  • jothi prakash

    public override bool OnDown(MotionEvent e)
    {
    return true;
    }

    please add this code without this it did not worked for me on xamarin android

  • rahul

    Hi Ravi i have one problem when i am creating Listener for fragment How i can call with

    private MainActivity.ClickListener clickListener;

    Thanks in Advance 🙂

    • rahul

      Thanks Problem is solved 🙂

      Many many thanks

  • ali

    Hi
    Thank you for your great tutorial.
    it was perfect.

  • Gabriel Menezes

    Master, great tutorial. Excuse my English, I am Brazilian. A question: I have a RecyclerView getting information from a JSON. I want to collect all the information obtained in the onClick and move to recycler view of a new activity using SharedPreferences. So I need to make a programmatically and not with data already saved. Any idea?

    • Hi Gabriel

      In RecyclerView click listener, you need to prepare an object of your json node and pass it to next activity. Follow these steps

      1. Implement you Model class as serializable. So that it can be passed as Object in Intent

      2. Get the selected json row node from the list of json node on click event. I am sure your recycler view will have an array list store all its rows values. In recycler view click event, using row index value you can get selected row from array list

      3. Pass the selected object to next activity by setting the values into Intent object.

  • Ifelere Oyetola

    This is very great. Thank you very much Ravi

  • Shivangi

    Please update the code and add “return true;” statement in onInterceptTouchEvent() method as i faced a problem that while clicking the gesture was taken infinite times in loop but after adding this it solved. Here is the code-

    @Override

    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
    clickListener.onClick(child, rv.getChildPosition(child));

    return true;

    }
    return false;
    }

    Thought its important so shared… N thanks a lot for this nice tutorial again!

  • Arvalon

    You can link to the whole project on GitHub?
    I can not understand who should implement the ClickListener interface?
    Why RecyclerTouchListener class static? Android Studio writes that “the Modifier ‘static’ not allowe here”. https://uploads.disquscdn.com/images/91dfdade75ca16820a12935dfc2e5cbf4ff57c7b3e86ac0b0b44a1d4179d3a3c.png

    • Instead of MainActivity.ClickListener, use ClickListener.

  • Ziigic

    Hello Sir Ravi,
    Sorry for my bad English. I wanna ask about recyclerview.
    I have 10 items in my recyclerview, then I wanna remove item 0,1,2
    like this example :

    for(Integer i = 0; i<3; i++){
    list.remove(i);
    adapter.notifyItemRemoved(i);
    adapter.notifyItemRangeChanged(i, list.size());
    }

    then the result I have :
    1,3,5,6,7,8,9,10
    item 1 not deleted, but my item 4 been deleted.

    Can you help me Sir…

    • Hi Ziigic, try the below code

      for(int i = 0; i < 3; i++){
      list.remove(i);
      }

      // notify data changes
      adapter.notifyDataSetChanged();

      • Ziigic

        Thank you Sir Ravi. 🙂

  • Sweeta

    Hello Sir,

    I am new in android, i follwed your tutorial,
    I am loading data from mysql using volley. All is going well.
    But problem is that when i scroll the recyclerview the position is getting change so the content is changed whenever view is recycle.
    How can i solve this problem??

    This is my Adapter Code:

    package info.androidhive.recyclerview;

    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.android.volley.toolbox.ImageLoader;

    import java.util.List;

    import info.androidhive.recyclerview.volley.AppController;

    public class MoviesAdapter extends RecyclerView.Adapter {

    private List moviesList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title, year, genre;
    public ImageView image;

    public MyViewHolder(View view) {
    super(view);
    title = (TextView) view.findViewById(R.id.title);
    genre = (TextView) view.findViewById(R.id.genre);
    year = (TextView) view.findViewById(R.id.year);
    image = (ImageView) view.findViewById(R.id.image);
    }
    }

    public MoviesAdapter(List moviesList) {
    this.moviesList = moviesList;
    }

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

    return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
    Movie movie = moviesList.get(position);
    holder.title.setText(movie.getTitle());
    holder.genre.setText(movie.getGenre());
    holder.year.setText(movie.getYear());
    ImageLoader imageLoader = AppController.getInstance()
    .getImageLoader();
    holder.year.setText(movie.getYear());
    imageLoader.get(movie.getImage(), ImageLoader.getImageListener(
    holder.image, R.mipmap.ic_launcher, R.mipmap.ic_launcher));
    }

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

    Before Scroll:

    https://uploads.disquscdn.com/images/85f7f1351d9ede675e31db104206a040919fc752d8815a4c731c70e7c1809bbc.jpg

    After Scroll:

    • Tenzin Choephel

      Hi i got the same result as u do. so i solved the problem by changing android:layout_height=”match_parent” to android:layout_height=”wrap_content” in movie_list_row (RelativeLayout Section)

      Hope it helps you.

      • thedroid

        EVERYONE should change this! Otherwise the whole recyclerview gets messed up!

  • Abhi Harsole

    Hello Ravi Sir, i tried the above example. I just added card view to the row item. after i run the code list displayed is ok. but when i scroll down the space between row item increases. why is this so happening ?

    • Abhilash Kumar

      I am getting the same issue. the height of each row increases to full screen

    • Arnav Bose

      Changing the Relative Layout Width and Height to ‘wrap_content’ in list_row_item.xml did the trick for me.

  • Lucas Barbosa

    não encontro de onde tirou o toolbar que tem na Main_Activity

  • sendoy

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    toolbar reference cant resolve…
    any idea?

    • @bcscoder

      have you add <android.support.v7.widget.Toolbar tag in your main layout?

  • MRITUNJAY PRATAP SINGH

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    r.id.toolbar not understand.

    we have declear android.support.v7.widget.Toolbar;

  • Jamshaid

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    r.id.toolbar not understand.

  • Nguyen Anh Quan

    you should write a note to explain about code below the each line code

  • Nguyen Anh Quan

    i cant use touch event, it has failed 🙁

  • Sankar Chakravarty

    it is showing toolbar error…..toolbar is not declared in the main xml, also even declaring toolbar in main xml, it unfortunately stopped. Plz help somebody….

  • EmiliePain

    Hello!
    I am getting the following error in content_main.xml:
    The surrounding layout (@layout/activity_main) did not actually include this layout.
    Remove tools:showIn=… from the root tag.

  • Madhu

    How to display it in horizontal orientation?

  • Mochamad Iqbal Dwi Cahyo

    @ravi8x:disqus thanks for your awesome tutorials :)))

    I prefer github code to check and fork your project, instead of download code using the .zip / .rar 🙂 *imho

  • Alan Kluz’em

    How to show the RecyclerView in the list manner instead of grid with images

    • This is already List manner only right?

      • ZAP

        Where is ClickListener in MainActivity. Which is accessed as private MainActivity.ClickListener clickListener; ?

  • Aashish Dahal

    Greetings, I took reference of your code to create an app of my own the difference is just the dataset. But my app only shows the last data added to the list. Please Help.

    • ZAP

      Where is ClickListener in MainActivity. Which is accessed as private MainActivity.ClickListener clickListener; ????

  • Thank you so much!

    • ZAP

      Where is ClickListener in MainActivity. Which is accessed as private MainActivity.ClickListener clickListener; ?

  • ZAP

    Where is ClickListener in MainActivity. Which is accessed as private MainActivity.ClickListener clickListener; ?

    • Ashfaque

      Actually it is RecyclerTouchListener.ClickListener clickListener;
      And here ClickListener is an interface which is inside of the class RecyclerTouchListener. By mistaken it is written outside.

  • George Brown

    Hi Ravi,
    Thanks for the tutorial. How could I add a Navigation Drawer to this example and be able to have fragments/screens with different layouts? (I’m creating an app with about 4 different “main screens”, i.e. Navigation Menu items. Some of the “main screens” will have sub screens, different layouts, buttons, forms, etc. )

  • Himanshu Shrimali

    Hi Ravi,
    The tutorial helped me a lot. So, thanks for that.
    But can you please recheck the code at line :-
    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener()

    This line is showing error near RecyclerTouchListener.ClickListener. So, for me , it worked by replacing “RecyclerTouchListener.ClickListener” with “ClickListener” only.

    Once again Thanks!!

  • vahid hasani

    Hi Ravi, thank you for your great tutorials. Would you please create a tutorial for multilevel RecyclerView like your multilevel ListView tutorial? It will be great.
    Thank You again for your best tutorials all over the internet.

  • Bassu Rai

    Hi Ravi

    Thank for sharing your great tutorial
    its work like charm at offline,
    but when i am fetching online data from mysql its return error in method

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

    in “MovieAdapter.class”
    that is
    java.lang.NullPointerException: Attempt to invoke interface method ‘int java.util.List.size()’ on a null object reference

    when my arraylist is empty
    how can i handle it

    Thanks in Advance !!!!.

    • You need to create an instance of moviesList before passing it to adapter. moviesList = new ArrayList() .. something like this.

  • riyaz ahmed

    says class DividerItemDecoration and RecyclerTouchListener are never used

  • harikrishna nallani

    how can i display xml data from assets folder by using xml pull parser pls help me harikrishna.nallani@gmail.com

  • Dave Byrne

    Hi Ravi,
    Another fantastic tutorial, thanks a lot.
    Having an issue similar to Arvalon below. Its having a problem with the ClickListener interface. I’ve changed the code above so that the interface is not public and RecyclerToughListener class is not static. These had to be done to eliminate errors. Though now my main activity (HomeFragment) cannot resolve symbol ClickListener. Here are some screenshots.

    https://uploads.disquscdn.com/images/e0dbfd181e9b7b18adcd158d933bc02df899049ff0516870425d5b60b7849b34.png

    https://uploads.disquscdn.com/images/5bff0f9296e3667910bac5782e4910bc2df409556e9360e1a83d99f5baf9c3a9.png

  • Redman

    There are few issues with clicklistner class Use the following one

    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    import android.view.View;

    public class RecyclerTouchListner implements RecyclerView.OnItemTouchListener {
    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListner(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
    this.clickListener = clickListener;
    gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
    return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null) {
    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
    }
    }
    });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
    clickListener.onClick(child, rv.getChildPosition(child));
    }
    return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

    public interface ClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
    }

    }

    • Use this one.

      import android.content.Context;
      import android.support.v7.widget.RecyclerView;
      import android.view.GestureDetector;
      import android.view.MotionEvent;
      import android.view.View;

      public final class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
      private OnItemClickListener mListener;

      public interface OnItemClickListener {
      public void onItemClick(View view, int position);
      }

      GestureDetector mGestureDetector;

      public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
      mListener = listener;
      mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
      @Override
      public boolean onSingleTapUp(MotionEvent e) {
      return true;
      }
      });
      }

      @Override
      public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
      View childView = view.findChildViewUnder(e.getX(), e.getY());
      if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
      mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
      }
      return false;
      }

      @Override
      public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
      }

      @Override
      public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

      }
      }

  • kevin purwono
    • Heri Hakim Setiawan

      i got the same issue…but i have not find the solution yet…
      can anyone solved that issue ?

      • Joshua Orotayo

        You have to set the size of the recycler view container to wrap_content. If its match_parent, it will just extend either way in bad ways

    • set height to wrap_content of parent layout in movie_list_row.
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
      android:layout_width="match_parent"
      android:layout_height="match_parent"

      • Thanks a lot.. I added this in movie_list_row

        android:layout_height=”wrap_content”

        this fixed the problem when scrolling.. 🙂

  • Scrolling won’t do. Results in 1 item per page, in the virtual devive and on my 5″ phone.

    • set height to wrap_content of parent layout in movie_list_row.

    • thank you, it’s fine now. I’ll continue the tutorial.

  • Khan

    @ambusy123:disqus @kevinpurwono:disqus @herihakimsetiawan:disqus
    Hey guys,
    I have found the solution I believe its not the best but it will be okay for now,
    Open your “movie_list_row.xml”

    android:layout_width=”match_parent” //Leave this and everything else as it is.
    android:layout_height=”match_parent”
    //Change android:layout_height=”match_parent” with android:layout_height=”60dp”

    • Rather set height to wrap_content of parent layout in movie_list_row and that will be ok.

  • “Guys you can also try this
    right click on your package name>new >activity>master details flow>finish.
    enjoy.”

  • Lee

    instead of DIVIDER why we cant do like this in the XML file

    //for Divider line create a Linear Layout after the Text View and Put back ground colour for the Linear Layout #####

    • You can do it, but it’s about performance. Using this you will loose the recyclerview performance.

  • Swapnil Bhikule

    hii
    I have 100 records but i want to show only 10 records in recyclerview on each scroll

    • Why you want to do that?

      • Swapnil Bhikule

        because of
        the need of user…..

        • If you use Custom adapter class, you don’t have to do anything. The adapter class already takes care of showing only necessary rows on the screen and add few when scrolled up or down (by doing recycling).

    • Pritam Dasgupta

      This one u have to put some grease on ur grey matter.. Hint:

      recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

      @Override
      public void onScrolled(RecyclerView recyclerView, int x, int y) {
      super.onScrolled(recyclerView, x, y);

      items = mRecyclerView.getChildCount();
      mtotalItems = linearlayout.getItemCount();

      ……………….

    • Do somthing like-
      rv_offers.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) {
      @Override
      public void onLoadMore(int page, int totalItemsCount) {
      // Triggered only when new data needs to be appended to the list
      // Add whatever code is needed to append new items to the bottom of the list
      getItemsReq();
      }
      });

      //And inside getItemsReq have a Integer pageCount and in every scroll insrease pageCount by one or // pageCount++ and send it to server and on behalf of that count server will return 10 or 20 //items(depends on your requirement) every time. Like the pageCount =0, server return 10 items so //add these 10 items in list and when you scroll again now pageCount =1, server will return another 10 //so add these 10 items in your list again.

      private void getItemsReq() {
      // final ProgressDialogBox pd = new ProgressDialogBox(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, getResources().getString(R.string.app_name), “Just a moment..!”, R.drawable.ic_launcher);
      showDialog();
      StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.URL_DATA,
      new Response.Listener() {
      @Override
      public void onResponse(String response) {
      try {
      Log.e(“Items”, response);
      hideDialog();
      // pd.hideDialog();
      //{“result”:[{“user_email”:”admin@gmail.com”,”user_id”:”40″,”user_active”:”1″,
      // “user_mobile_no”:”9876543210″,”user_fname”:”admin”}],”message”:”Successfully Login”}
      JSONObject jsonObj = new JSONObject(response);

      if (jsonObj != null) {
      if (jsonObj.has(“status”)) {
      if (jsonObj.getString(“status”).equalsIgnoreCase(“true”)) {
      pageCount++;
      if (jsonObj.has(“result”)) {
      JSONArray jsonArray = jsonObj.getJSONArray(“result”);

      for (int i = 0; i < jsonArray.length(); i++) {

      JSONObject jsonChildNode = jsonArray
      .getJSONObject(i);

      String item_id = jsonChildNode.getString("item_id");
      String item_name = jsonChildNode.getString("item_name");
      String description = jsonChildNode.getString("description");
      String price = jsonChildNode.getString("price");
      String discount_price = jsonChildNode.getString("discount_price");

      String image = jsonChildNode.getString("image");

      items_list.add(new ItemsDTO(item_name,description,price,image,item_id,discount_price));

      }
      adpter.notifyDataSetChanged();
      }

      } else {
      Toast.makeText(ItemsActivity.this, "No data found", Toast.LENGTH_LONG).show();
      }

      }
      }

      } catch (JSONException e) {
      e.printStackTrace();
      }
      }
      },
      new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
      error.printStackTrace();
      // pd.hideDialog();
      hideDialog();

      }
      }
      ) {
      @Override
      protected Map getParams() {
      Map params = new HashMap();
      // the POST parameters:
      params.put(“area_code”, session.getArea().get(SessionManager.KEY_AREA_ID));
      params.put(“category”, session.getCategoryID().get(SessionManager.KEY_CATEGORY_ID));
      params.put(“sub_category”, session.getSubCategoryID().get(SessionManager.KEY_SUBCATEGORY_ID));
      params.put(“page”, String.valueOf(pageCount));

      return params;
      }
      };
      Volley.newRequestQueue(ItemsActivity.this).add(postRequest);
      Log.e(“postRequest”, postRequest.toString());
      postRequest.setRetryPolicy(new RetryPolicy() {
      @Override
      public int getCurrentTimeout() {
      return 50000;
      }

      @Override
      public int getCurrentRetryCount() {
      return 50000;
      }

      @Override
      public void retry(VolleyError error) throws VolleyError {

      }
      });

      }

  • Jayraj Patel

    I want to open a new activity instead of creating a Toast when an item int the recycler View is clicked. How am I supposed to do that?

    • Chutchatut Sutichavengkul

      Create an intent

    • Jovylle Bermudez (Twero)

      Do another research dude.
      this here focuses on recycler view

      i recommend you searching

      “android goto another activity”

      then the right code you find the best for you

      put it in the listener where the toast is located

      Good luck God Bless.

  • Jovylle Bermudez (Twero)

    Hello Sir.
    i am bit disappointed you have not included the main activity xml file

    canyou add it on the next update

    • Jovylle Bermudez (Twero)

      The links are currently not available Sir.
      can you also fix that later.

      i am your QA for the day

      ahahah

      —————————
      opps i tried it again downloading it with facebook
      not gmail.

      its working

    • Please get the file from downloaded source code.

  • Jijo Alexander

    hi ravi,
    how we can got a single image in another activity from server, when clicking that image in recycler view using on item click. please help

  • Tushar

    From where can i divider color?

  • sumeet guha

    Hi Ravi,
    How can we implement expandable list item, through RecyclerView, any idea/suggestion?
    Thanks,
    Sumeet.

  • swapnilsaha2010

    in “movie_list_row.xml”, layout_height of RelativeLayout should be “wrap_content”. Otherwise, one item fills whole screen vertically so you don’t see another.

    • Yeah, this was due to recent changes in support library.

  • Damien Duflot

    Hi thanks for the tutorial
    Can we force the recyclerView to reposition itself to always display the first line entirely?

  • Kasa Sathish

    I am not getting the list displayed. Only, The first item in the list is displaying. can someone help me out of this

    • Campo Fertilidade

      As @swapnilsaha2010:disqus said: In “movie_list_row.xml”, layout_height of RelativeLayout should be “wrap_content”. Otherwise, one item fills whole screen vertically so you don’t see another.

      • Kasa Sathish

        Thanks and it works. I already figured it.

  • Tamil Selvan

    How to access all the items ie visible and invisible items in the recycler view;

  • Tamil Selvan

    Please help me as soon as possible

  • PRADEEP KUMAR

    Hi Ravi please Help me with Calender Click..i am doing a project in which click on date in calendar should open a Inent with RecyclerView.

    Please help me..searched online for 4 days..i didnt found any solution

  • Aqsa Shahid

    Hi ravi i wanted to ask wha if we need pagination inside the recyclerview..

    • Do somthing like-
      rv_offers.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) {
      @Override
      public void onLoadMore(int page, int totalItemsCount) {
      // Triggered only when new data needs to be appended to the list
      // Add whatever code is needed to append new items to the bottom of the list
      getItemsReq();
      }
      });

      //And inside getItemsReq have a Integer pageCount and in every scroll insrease pageCount by one or // pageCount++ and send it to server and on behalf of that count server will return 10 or 20 //items(depends on your requirement) every time. Like the pageCount =0, server return 10 items so //add these 10 items in list and when you scroll again now pageCount =1, server will return another 10 //so add these 10 items in your list again.

      private void getItemsReq() {
      // final ProgressDialogBox pd = new ProgressDialogBox(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, getResources().getString(R.string.app_name), “Just a moment..!”, R.drawable.ic_launcher);
      showDialog();
      StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.URL_DATA,
      new Response.Listener() {
      @Override
      public void onResponse(String response) {
      try {
      Log.e(“Items”, response);
      hideDialog();
      // pd.hideDialog();
      //{“result”:[{“user_email”:”admin@gmail.com”,”user_id”:”40″,”user_active”:”1″,
      // “user_mobile_no”:”9876543210″,”user_fname”:”admin”}],”message”:”Successfully Login”}
      JSONObject jsonObj = new JSONObject(response);

      if (jsonObj != null) {
      if (jsonObj.has(“status”)) {
      if (jsonObj.getString(“status”).equalsIgnoreCase(“true”)) {
      pageCount++;
      if (jsonObj.has(“result”)) {
      JSONArray jsonArray = jsonObj.getJSONArray(“result”);

      for (int i = 0; i < jsonArray.length(); i++) {

      JSONObject jsonChildNode = jsonArray
      .getJSONObject(i);

      String item_id = jsonChildNode.getString("item_id");
      String item_name = jsonChildNode.getString("item_name");
      String description = jsonChildNode.getString("description");
      String price = jsonChildNode.getString("price");
      String discount_price = jsonChildNode.getString("discount_price");

      String image = jsonChildNode.getString("image");

      items_list.add(new ItemsDTO(item_name,description,price,image,item_id,discount_price));

      }
      adpter.notifyDataSetChanged();
      }

      } else {
      Toast.makeText(ItemsActivity.this, "No data found", Toast.LENGTH_LONG).show();
      }

      }
      }

      } catch (JSONException e) {
      e.printStackTrace();
      }
      }
      },
      new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
      error.printStackTrace();
      // pd.hideDialog();
      hideDialog();

      }
      }
      ) {
      @Override
      protected Map getParams() {
      Map params = new HashMap();
      // the POST parameters:
      params.put(“area_code”, session.getArea().get(SessionManager.KEY_AREA_ID));
      params.put(“category”, session.getCategoryID().get(SessionManager.KEY_CATEGORY_ID));
      params.put(“sub_category”, session.getSubCategoryID().get(SessionManager.KEY_SUBCATEGORY_ID));
      params.put(“page”, String.valueOf(pageCount));

      return params;
      }
      };
      Volley.newRequestQueue(ItemsActivity.this).add(postRequest);
      Log.e(“postRequest”, postRequest.toString());
      postRequest.setRetryPolicy(new RetryPolicy() {
      @Override
      public int getCurrentTimeout() {
      return 50000;
      }

      @Override
      public int getCurrentRetryCount() {
      return 50000;
      }

      @Override
      public void retry(VolleyError error) throws VolleyError {

      }
      });

      }

  • Now RecyclerView supports OnClickListener, so you just need to put it in the MyViewHolder, like this:
    https://uploads.disquscdn.com/images/6da6250ee66b9227dd243d45405bcccc9ff97648653a1653968faa89e5caaad1.png

    • syukron Rizqi

      how to get the item position on MyViewHolder ?

      • Игорь Безека

        getAdapterPosition()

  • Aqsa Shahid

    hey how am i going to use swipeRefreshLayout in RecyclerView

  • Khurria Zafar

    Hey.. Thanx for the tutorial..
    How can we Change toolbar on item Long click?

  • Srinath VS

    Hi how we can scroll selection border from position to position with animation in recyclerview

  • player of_theworld

    thank you

  • sazzad kanon

    According to the Declaration (MainActivity.ClickListener) the interface should be declared into MainActivity class. bt u declared in the RecyclerTouchListener.java class.. even before the general class declaration. does it make any sense?

    • Seems to be a mistake. It happened because of Android Studio auto import. I’ll update the code.

      • sazzad kanon

        Thanks a lot sir..

      • Muhammad Reza

        is it fix already sir?

  • kunal garg

    for the same code above of recycler view if i had to add three edit text and on clicking add button my content of edit text is displayed below in recycler view .
    what could be done??
    I have just only added three edit text and an add button in activity_main.xml after that please help me with the process for the same code of recyclerview.

    • Add the same in movie_list_row.xml

      • kunal garg

        thnku for your help!
        Now please can you tell me how to add a radio button or check box for each row,means what changes will be taking place in code above

  • Ken Malinao

    Sir ravi? Can I have a request? If its okay with you. Can you make me a code with a very simple listview with just 5 lists. Which has Title and Singer say Title 1 Singer 1, Title 2 Singer 2, …
    And when Title 1 is clicked, Activity 1 will open. When Title 2 is clicked, Activity 2 will open. Im confused about the code above. Im a beginner only. Thank you a lot sir ravi. More power.

  • Ken Malinao

    I think I got it. Thank you sir. But, how can I make every item open a new activity?
    Item 1 >> Activity 1
    Item 2 >> Activity 2……

    • Ash Ravi

      Just add intent in the onclick under onitemTouchListener

      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
      @Override
      public void onClick(View view, int position) {
      Movie movie = movieList.get(position);
      Toast.makeText(getApplicationContext(), movie.getTitle() + ” is selected!”, Toast.LENGTH_SHORT).show();
      if(position==0){//first item and activity 1)
      Intent i=new Intent(MainActivity.this,your activity1.class);
      StartActivity(i);
      }
      if(position==1){//second item and activity 2
      Intent i=new Intent(MainActivity.this,your activity2.class);
      StartActivity(i);
      }
      }

      @Override
      public void onLongClick(View view, int position) {

      }
      }));

      • Ken Malinao

        Thank you sir ravi. How to make the list in alphabetical? Without adjusting the arrangements inside the mainacrivity class.?

  • arti

    hello sir,
    I want to add one recyclerview value in another activity’s recyclerview by click on button that available in first recyclerview but how can i achieve i try with getting value of object in onBindView method of ViewHolder class in another activity …please sir tell me what i do to passing values between to recyclerview in android

  • First of all thank you for the tutorial Ravi Tamada..

    I found there was problem in selection of Home from Navigation Drawer for the second time it’s not going back to home because of there was a mistake in case 0 of onNavigationItemSelected() in switch case. So I just changed

    from: case R.id.home:
    to: case R.id.nav_home:

    This may helps some one.

  • Parvesh Monu

    Hello Sir I added a button in my custom layout but when I clicking on button then both on click of button and recylerTouch Listener calling what i am doing wrong.

    • arti

      try this code it is working in my example i hope its also helping you
      recyclerView.setOnTouchListener(new View.OnTouchListener()
      {

      @Override
      public boolean onTouch(View v, MotionEvent event) {
      final Button btd=(Button)findViewById(R.id.button_delete);

      btd.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

      Intent in=new Intent(getApplicationContext(),DeleteActivity.class);
      // in.putExtra(“arti”,txts.getText().toString());
      startActivity(in);

      }
      });

      return false;
      }
      });

  • Bishwajeet Biswas

    Hi, i need to display items using RecyclerView and where i can add/remove/edit items dynamically but the problem is after using swapAdapter method adding item is not working.

  • Summoner’s Lizzy

    A humble Request :
    Dear sir,

    I’ve been a great fan of your work and loved em all but there’s one thing that i would like to suggest that i believe would make almost all your viewers more happy.The one thing that i would like to suggest is for you to add the codes of all the different classes and layouts+manifest at the end of the guides so that we might be able to save lots of time downloading the actual codes,building the gradles and what nots thus enabling us to take a quick look at the points/lines of codes that we needed.

    Keep up the great work

    Lizzy

    • Yes, I am adding the necessary files always. But adding all files in the article makes it lengthy and add confusion to theme concept.

  • Sh Ekh AR

    waiting for your article on geo fencing sir….

  • Muhammad Rahmatullah Rahman

    in android SDK 25 DividerItemDecoration added so we don’t need to write a dozen line of code anymore just for create an item divider here is the documentation https://developer.android.com/reference/android/support/v7/widget/DividerItemDecoration.html
    anyway I’ve been following this great tutorial, keep it up ravi sir

  • Rony smile

    Hello Ravi Sir, really a big fan of yours. Because of you I am able to do my projects in my office.Sir can you please upload tutorials on Reactive Programming in Android/Java(Rx-Java/Android),Inversion of Control,Dagger2, Geofencing because I got a new project where I need to include these new concepts.

    • Hi Rony

      I need to work a lot to get your request done.

      • Rony smile

        Take your time sir, but please include these concepts on your blog.

  • Rizwan hassan

    It is awesome
    Thanks

  • Kidus M. Tekeste

    wondering if implementing reyclerview is possible in fragment not activity???
    is it possible to add recyclerview in our fragment UI???

    • Shahrukh khan

      Yes it’s possible. I implemented it in fragment only. Go for it!

    • Tunç Yanık

      How can i do this ? ı want to impement this recycleview in fragment

    • Daksh Gargas

      Create an interface in your fragment and implement it in your MainActivity or the ViewGroup class for your fragment and perform the functions into that method.
      You also need to call this method in your RecylerTouchListener as well

      for instance
      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
      @Override
      public void onClick(View view, int position) {
      drawerListener.onDrawerItemSelected(view, position); //Over here
      drawerLayout.closeDrawers(); //to close the drawer, lol!
      }

  • Felipe Peña

    Hi ravi
    How can I get the adapter position and path of file, because when I use

    Toast.makeText(MainActivity.this,””+recycler_adapter.getItemId(position),Toast.LENGTH_SHORT).show();

    only show -1

    • You have to use the position on the arraylist you used for recyclerview.

      • Felipe Peña

        its works thanks

      • ahmad

        hello ravi, when i am putting the public interface ClickListener i have an error red line under the the (public interface Clicklistener) it says (Clicklistener is public, should be declared in a file named Clicklistener.java) also (MainActivity.ClickListener ) ClickListener is red (cannot resolve symbol ClickListener) so can you help me pleas, thank u

  • Filipe Braga

    How Can I do Divider/Separator between objects in the same register of RecyclerView?

    For example: I would like to do something like a Sheet, with some columns for row.

    • Ziigic

      1. Create a class DividerItemDecoration that’s extends RecyclerView.ItemDecoration and create your own separator style
      2. Then on other class that’s contain RecyclerView , you can use this :
      recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

  • Filipe Braga

    Hi Ravi and friends,

    I made this RecyclerView in my project, the start screen is OK, but when I scrool the RecyclerView objects doesn’t stay with the same lenght and ocupate full space of the RecyclerView (each one).

    How Can I to resolve this? Thanks

    Picture 1:
    https://uploads.disquscdn.com/images/7c58e4c9895e65dcad7b3ad0dda0f11561cd37c211599bbf911275001d4490d8.png

    Picture 2: https://uploads.disquscdn.com/images/db8c4cbef78c82ac088cc17932fa4cea0ea6fa5703d30c878d8fcaea9c805cb0.png

    • Ziigic

      Sorry, I don’t understand what you want.., can you explain it ? XD

      • Filipe Braga

        Sorry if my english is wrong or I don’t explain better my dout.

        The Picture 1 is like my app started. The RecyclerView (in white color) is ok. After, when I slide the RecyclerView, for to view more itens, the screen stay like Picture 2, with each item in full viewable screen.

        Like if RecyclerView don’t keep configured size of movie_list_row.xml.

        Understand?

        Thanks

        • Ziigic

          Don’t worry, Sorry for my bad english too. XD

          Oh..I got it. When you load more item, then your newitem1, newitem2, newitem3, etc. showed in full page on each item ?

          • Filipe Braga

            Ok, it’s very good.

            Actually, itens in my app are prepared before create RecyclerView according Picture 1 (show 9 itens), but like there are 16 itens in example, I slide in RecyclerView scroll to view other itens.

            Only when I click and slide the screen does not display more than one item as Picture 1, resizing upcoming itens according Picture 2.

          • Ziigic

            Can you share your project in github ? I’ll try to help you.

          • Filipe Braga

            Ziigic, the Prasanna Kumar found the problem. I changed the xml layout insted of match parent for wrap content.

            Thanks

    • Prasanna Kumar

      I think you would have used Mathc parent in your xml layout insted of match parent try warp parent

      • Filipe Braga

        Very good!! It’s all right now!

        Thanks!!

    • Priyanjul Johari

      Use ‘wrap_content’ instead of ‘match_parent’ in layout_height of relative layout movie_list.xml

  • anmol gandhi

    Hello Sir,
    I am developing an android project and using a chatbot client in it which i built before.The problem is i am not able to place buttons in a layout, because as that layout is inflated again and again for every message so buttons are coming in every message i want to fix them for a particular message or when a condition occur then only the buttons should come, not in every message.
    It would be grateful if you can help with something.
    Thanks in advance.

  • pranay sawant

    Hello,

    Recycler looks great, but when I scrolled it down, completely messed up. why is it so? if I scroll down it messed the list. I tried holder.setIsRecyclable(false); But no luck

    • Paul

      Try to change the value of heigh in movie_list_row.xml from match_parent to wrap_content

      • jay Keerti (jaykeerti123)

        Thanks i had the same issue!!

  • Boopathi

    when i build gradle with this below code it having bug on scrolling.but for build tool version 23.0.2 it works perfectly
    “`

    apply plugin: ‘com.android.application’

    android {
    compileSdkVersion 25
    buildToolsVersion “25.0.3”

    defaultConfig {
    applicationId “info.androidhive.recyclerview”
    minSdkVersion 19
    targetSdkVersion 25
    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:25.3.1’
    compile ‘com.android.support:design:25.3.1’
    compile ‘com.android.support:recyclerview-v7:25.3.1’
    }

    “`

  • Veeresh Shirol

    Thanks Ravi:):) It’s a Great Learning site.

  • kamini mathur

    I wil try this code but problem is that only one record are display……not display evry record…..no error occured can u say me what is problem?

    and second thing why use Toolbar??????

  • Siddharth Dhavan

    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());

    what does this line explain?? what is e.getX() and e.getY() ?

  • Raghavendra

    I’m getting ” recyclerView.getChildPosition(child))”,”, rv.getChildPosition(child));” as deprecated method. How can overcome this error ,and Why this error is arising .Can anyone help me with this? please,,,,,

    @Override
    public void onLongPress(MotionEvent e) {
    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null) {
    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
    }
    }
    });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
    clickListener.onClick(child, rv.getChildPosition(child));
    }
    return false;
    }

  • Youssef Wagih

    it’s very good Tutorial 🙂

  • Anurag Hisaria

    Great tutorial sir, thanks.
    Sir, I want to know how to create a lock screen app widget in Android. Could you please help me with that, or post some tutorial if available?
    Thanks in advance.

  • Thats Enam

    -1 complex

  • prabhakaran s

    i have used pagination in recyclerview, after append new data to the previous data that time my recyclerview once again scrolled top position what i do ?

  • No you shouldn’t add a separator by creating a new view. You have to add the separator via addItemDecoration(). Check the 3rd point in the article.

  • hamza dabir

    i couldn’t implement clicklistener interface in same class also recycle touch listener class cannot be implemented as static ..

  • Mukhriddin Ruziboev

    Dear Ravi Tamada,
    I would like to ask you about my current issue. The problem is that I have one model includes 4 model and I wanted to make Adapter for this model but I could not manage what return in getItemCount() method. I really appreciate it if you help me to handle this problem.
    Best regards,
    Mukhr

  • Gharelo Totkay

    How can i make recyclerview items make clickable in such a way as to open a seperate activity against each row item.

  • Yes, you can.

  • Hùng Kim Văn

    i get the same, but i solved
    first u cut the interface and paste into class RecyclerTouchListener
    second u replace “MainActivity” by “RecyclerTouchListener
    it’ll ok!