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

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

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    // ..
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //..

    // RecyclerView
    implementation 'com.android.support:recyclerview-v7:26.1.0'
}

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>

5. Open dimens.xml located under res ⇒ values and add the dimensions.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="row_padding_vertical">10dp</dimen>
</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.

6. 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;
    }
}

7. 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="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:orientation="vertical"
    android:paddingBottom="@dimen/row_padding_vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/row_padding_vertical">

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

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

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

</RelativeLayout>

8. 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();
    }
}

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

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

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. Custom Divider Line with Margins

The default divide occupies the full width of item row. In some scenarios you might wanna add margin to divider line. For that you need to create a custom divider class by providing necessary margins and divider color.

10. Create a class named MyDividerItemDecoration.java and extend the class from ItemDecoration and use addItemDecoration() method to display the divider.

package info.androidhive.recyclerview;

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

/**
 * Created by Ravi on 30/10/15.
 * updated by Ravi on 14/11/17
 */
public class MyDividerItemDecoration 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;
    private Context context;
    private int margin;

    public MyDividerItemDecoration(Context context, int orientation, int margin) {
        this.context = context;
        this.margin = margin;
        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 + dpToPx(margin), top, right - dpToPx(margin), 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 + dpToPx(margin), right, bottom - dpToPx(margin));
            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);
        }
    }

    private int dpToPx(int dp) {
        Resources r = context.getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }
}

11. Open MainActivity.java and set the custom decoration using addItemDecoration() method before setting the adapter. Below margin of 16dp is added on left and right side of divider line.

recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));

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

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

5. Displaying Horizontal Scrolling RecyclerView

If you want to display the RecyclerView in Horizontal manner, you can do that just by changing a single line of code. All you have to do is provide direction to layout manager i.e LinearLayoutManager.HORIZONTAL as shown below. Also don’t forget to keep your row layout width to WRAP_CONTENT.

// horizontal RecyclerView
// keep movie_list_row.xml width to `wrap_content`
RecyclerView.LayoutManager mLayoutManager = 
new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
android recyclerview horizontal scrolling

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

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

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

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(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);
    }
}

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.DividerItemDecoration;
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);

        // vertical RecyclerView
        // keep movie_list_row.xml width to `match_parent`
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());

        // horizontal RecyclerView
        // keep movie_list_row.xml width to `wrap_content`
        // RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);

        recyclerView.setLayoutManager(mLayoutManager);

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

        // adding custom divider line with padding 16dp
        // recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.setAdapter(mAdapter);

        // row click listener
        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();
    }

    /**
     * Prepares sample data to provide data set to adapter
     */
    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);

        // notify adapter about data set changes
        // so that it will render the list with new data
        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 articles that explains advanced RecyclerView that combines CardView and RecyclerView in a grid fashion, adding Swipe to Delete and Undo and adding Search Filter.

1. Android working with Card View and Recycler View

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

2. Android adding RecyclerView Swipe to Delete and Undo

recycler-view-swipe-delete-undo-example

3. Android RecyclerView adding Search Filter

android-recyclerview-search-filter
Change Log

Updated On 3rd Sep 2016 (Content Update, Bug fixes)
19th Nov 2017 (Content Update, Latest changes in support library)
Subscribe
Notify of
guest
558 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kamran
Kamran
4 years ago

thx Ravi

David Maraba S
David Maraba S
4 years ago

Nice

علي
علي
4 years ago

link doesn’t open!!

Ravi Tamada
4 years ago
Reply to  علي

Which link?

علي
علي
4 years ago
Reply to  Ravi Tamada

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

Ravi Tamada
4 years ago
Reply to  علي

Please try in some other browser.

Uh Oh...
Uh Oh...
4 years ago
Reply to  Ravi Tamada

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.

Ravi Tamada
4 years ago
Reply to  Uh Oh...

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
Abdel
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Abdel

🙂

Vishal
Vishal
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Vishal

Thanks Vishal

Ravi
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Ravi

Really 🙂

Ravi
Ravi
4 years ago
Reply to  Ravi

This might be usefull to all who are using recyclerView http://androidgig.com/addheaderview-in-recyclerview/

ravin
ravin
4 years ago

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.

Ravi Tamada
4 years ago
Reply to  ravin

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

Joshi Pinak
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Joshi Pinak

You are welcome 🙂

newDevL
newDevL
4 years ago

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

Arvind Yadav
Arvind Yadav
4 years ago
Reply to  Ravi Tamada

hi Ravi, your tutorial is best and the given link is also best ,but i want both touch listener and swipe to dismiss.Like in gmail app when we swipe left to right or vice versa item deleted ,and when we touch any item we reach to new activity.How i can do like that?

Chirag thaker
Chirag thaker
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Chirag thaker

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

Chirag thaker
Chirag thaker
4 years ago
Reply to  Ravi Tamada

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

Ravi Tamada
4 years ago
Reply to  Chirag thaker

I’ll check. Thank you

Taimur Hassan
Taimur Hassan
4 years ago

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.

Ravi Tamada
4 years ago
Reply to  Taimur Hassan

In this article I have set ripple effect background using android:background=”?android:attr/selectableItemBackground” in movie_list_row.xml. You can create a custom drawable and use it as background.

Here you can see how to create drawable and use it for recycler view item background.
http://stackoverflow.com/questions/25392722/background-selector-in-recyclerview-item

Taimur Hassan
Taimur Hassan
4 years ago
Reply to  Ravi Tamada

Thank you man 🙂

Ravi Tamada
4 years ago
Reply to  Taimur Hassan

You are welcome 🙂

Srivatsa Ramesh
Srivatsa Ramesh
4 years ago

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

Ravi Tamada
4 years ago

You have to add them in movie_list_row.xml layout.

Shubham Patwa
Shubham Patwa
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Shubham Patwa

Simple add the CardView to movie_list_row.xml

FaisalHyder
FaisalHyder
4 years ago
Reply to  Shubham Patwa

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

FaisalHyder
FaisalHyder
4 years ago

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

Ravi Tamada
4 years ago
Reply to  FaisalHyder

Yeah, we can do that. Thank you 🙂

Hardik Mehta
Hardik Mehta
4 years ago

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
Suraj mistry
4 years ago

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
Suraj mistry
4 years ago

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
Suraj mistry
4 years ago

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
Arslanali
4 years ago

The minimum version API using Recycler View?

harin kaklotar
harin kaklotar
4 years ago
Reply to  Arslanali

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

Arslanali
Arslanali
4 years ago
Reply to  harin kaklotar

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

Arslanali
Arslanali
4 years ago
Reply to  harin kaklotar

Thank you very much for your response

harin kaklotar
harin kaklotar
4 years ago
Reply to  Arslanali

your welcome 🙂

Jévan Weekes
Jévan Weekes
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Jévan Weekes

RecyclerView is same as ListView. Try as mentioned in below article. All the images were loaded from an url.

http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

King Kazma
King Kazma
4 years ago

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

Darragh O'Flaherty
Darragh O'Flaherty
4 years ago
Reply to  King Kazma

write a method that returns an ArrayList with you cursor and all the rest in that.

Slidnerd had good example of this
https://github.com/slidenerd/materialtest/blob/master/app/src/main/java/materialtest/vivz/slidenerd/database/DBMovies.java
look at the readMovies method.

Then just call that in the MainActivity

Anubhav
Anubhav
4 years ago

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

Clay24g
Clay24g
4 years ago

Great material design tutorials. Keep them coming.

ilham fadhli
ilham fadhli
4 years ago

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

Umar
Umar
4 years ago

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

iJavaYou
iJavaYou
4 years ago

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
Sharoon Amjid
4 years ago

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
Villa Nanda
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Villa Nanda

Oh okay. I’ll check it.

Thanks.

Isuru Madusanka
4 years ago
Reply to  Ravi Tamada

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

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

Ravi Tamada
4 years ago

Yeah, I’ll update.

Lijo Varghese
Lijo Varghese
4 years ago
Reply to  Ravi Tamada

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 :comment image

Atul
Atul
4 years ago

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
Bruno Chichava
4 years ago
Reply to  Villa Nanda

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

Isuru Madusanka
4 years ago

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

Shujhal Singh
Shujhal Singh
4 years ago

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

trinadhkoya
4 years ago
Reply to  Shujhal Singh

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
Shujhal Singh
4 years ago
Reply to  trinadhkoya

thanks sir

vikas kumar
vikas kumar
4 years ago

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

Ravi Tamada
4 years ago
Reply to  vikas kumar

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
ARASHI Funsho
4 years ago

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
Dimas syuhada
4 years ago
Reply to  ARASHI Funsho

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
ARASHI Funsho
4 years ago
Reply to  Dimas syuhada

Thanks Dimas, will try what you suggested and revert.

ARASHI Funsho
ARASHI Funsho
4 years ago
Reply to  Dimas syuhada

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

Ravi Tamada
4 years ago
Reply to  ARASHI Funsho

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
ARASHI Funsho
4 years ago
Reply to  Ravi Tamada

Okay, but how do i go about doing that?

ARASHI Funsho
ARASHI Funsho
4 years ago
Reply to  Ravi Tamada

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
Jovie Brett Bardoles
4 years ago

Thanks alot for the very well made tutorials man!

Ravi Tamada
4 years ago

You are welcome 🙂

Jovie Brett Bardoles
Jovie Brett Bardoles
4 years ago
Reply to  Ravi Tamada

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
Atul
4 years ago

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
hitesh810
4 years ago
Reply to  Atul

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

Lewis
Lewis
4 years ago
Reply to  Atul

yeahh that’s right

Atul
Atul
4 years ago

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

Ravi Tamada
4 years ago
Reply to  Atul

Thanks Atul.

Vikram maxim
Vikram maxim
4 years ago

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

Rajkumar prajapati
Rajkumar prajapati
4 years ago
Reply to  Vikram maxim

say me what to do?

hitesh810
hitesh810
4 years ago
Reply to  Vikram maxim

Use this-

LinearLayoutManager layoutManager

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

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

myList.setLayoutManager(layoutManager);

Rajkumar prajapati
Rajkumar prajapati
4 years ago
Reply to  hitesh810

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

hitesh810
hitesh810
4 years ago

add toast message inside onclick listner metod

Sachin Rajput
Sachin Rajput
4 years ago
Reply to  hitesh810

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
Umut Dönmez
4 years ago

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

richest man alive
richest man alive
4 years ago

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
tuan phuong tran
4 years ago

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
Vijender R
4 years ago

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

ARASHI Funsho
ARASHI Funsho
4 years ago

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
Aiswarya olakkal
4 years ago

thank you Ravi, It’s great work

Ravi Tamada
4 years ago

You are welcome 🙂

Nitin Gandge
Nitin Gandge
4 years ago
Reply to  Ravi Tamada

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

In which file I have to add ToolBar?

Ravi Tamada
4 years ago
Reply to  Nitin Gandge

Have you added toolbar in your layout file?

Nitin Gandge
Nitin Gandge
4 years ago
Reply to  Ravi Tamada

In which layout file?

Prajwal achar
Prajwal achar
4 years ago

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.

Ravi Tamada
4 years ago
Reply to  Prajwal achar

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

Prajwal achar
Prajwal achar
4 years ago
Reply to  Ravi Tamada

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
taufiq rachman
4 years ago

awesome tutorial. how to create menu on the onLongClick?

tarun jain
tarun jain
4 years ago

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

gorrox23
gorrox23
4 years ago
Reply to  tarun jain

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

|/|@¥@|||€
|/|@¥@|||€
4 years ago

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

Ravi Tamada
4 years ago
Reply to  |/|@¥@|||€

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

|/|@¥@|||€
|/|@¥@|||€
4 years ago
Reply to  Ravi Tamada

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.

|/|@¥@|||€
|/|@¥@|||€
4 years ago
Reply to  Ravi Tamada

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();

}

}

}

trinadhkoya
4 years ago
Reply to  |/|@¥@|||€

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
}

|/|@¥@|||€
|/|@¥@|||€
4 years ago
Reply to  trinadhkoya

ohk thanks sir 🙂

trinadhkoya
3 years ago
Reply to  |/|@¥@|||€

You are most Welcome ! @|/|@¥@|||€

Deep Gosalia
Deep Gosalia
4 years ago

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)

ashfaque ahmed
ashfaque ahmed
4 years ago
Reply to  Deep Gosalia

You can learn with the help of Android bootcamp training https://www.youtube.com/playlist?list=PLE953C0B85B50AB62

Troy Chuinard
Troy Chuinard
4 years ago

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
Unil Gandhi
4 years ago
Reply to  Troy Chuinard

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
Salman Saleem
4 years ago

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

Manik
Manik
4 years ago

Thanks…

Ankit Kumar
Ankit Kumar
4 years ago

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
Shubham Yadav
4 years ago
Reply to  Ankit Kumar

wrap_content the height of the row_list layout will solve your problem

558
0
Would love your thoughts, please comment.x
()
x