RecyclerView Simple Example in Android.

By | March 25, 2016

The RecyclerView widget is a more advanced and flexible version of ListView.
This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events.

You can find of the my previous posts on ListViews below

1. Custom ListView in Android

2. Filter a ListView

3. Faster Loading ListViews

4. Lazy Loading ListViews by loading values from Sever – Php

Recycler ListView Android

The RecyclerView class simplifies the display and handling of large data sets by providing:

  • Layout managers for positioning items
  • Default animations for common item operations, such as removal or addition of items

RecyclerView provides these built-in layout managers:

  • LinearLayoutManager shows items in a vertical or horizontal scrolling list.
  • GridLayoutManager shows items in a grid.
  • StaggeredGridLayoutManager shows items in a staggered grid.

    To create a custom layout manager, extend the RecyclerView.LayoutManager class.

    Once you have added a RecyclerView widget to your layout, obtain a handle to the object, connect it to a layout manager, and attach an adapter for the data to be displayed:

    Before you start you need these in the module build.gradle.

    I am using Picasso library for downloading images for each row. So please add library dependency for that also. You can download Picasso library from here.

    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:+'
        compile 'com.android.support:cardview-v7:23.0.+'
        compile 'com.squareup.picasso:picasso:2.5.0'
    }
    

    This is our main layout which contains the RecyclerView.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.coderzheaven.reyclerviewexample.MainActivity"
        tools:showIn="@layout/activity_main">
    
        <view
            android:id="@+id/recycler_view"
            class="android.support.v7.widget.RecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true" />
    
    </RelativeLayout>
    

    The MainActivity will look like this.

    package com.coderzheaven.reyclerviewexample;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        private RecyclerView mRecyclerView;
        private MyRecyclerAdapter adapter;
        private static final String TAG = "MainActivity";
        private ArrayList<ListItem> allList;
        public static final String URL1 = "http://i.forbesimg.com/media/lists/companies/apple_416x416.jpg";
        public static final String URL2 = "http://1.bp.blogspot.com/-PDCZL0FnXQQ/VbktgUGz2jI/AAAAAAAAKL4/ESw_62l5AbE/s1600/500px-android-logo_svg.png";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
            mRecyclerView.setHasFixedSize(true);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    
            setList();
    
            adapter = new MyRecyclerAdapter(MainActivity.this, allList);
            mRecyclerView.setAdapter(adapter);
    
        }
    
        public void setList() {
    
            allList = new ArrayList<>();
    
            for (int i = 0; i < 100; i++) {
                ListItem item = new ListItem();
                item.setTitle("Sample Demo on Android RecyclerView. Its efficient than ListView and Easy");
                item.setThumbnail((i % 2 == 0) ? URL1 : URL2);
                allList.add(item);
            }
    
        }
    
    }
    

    Now the Adapter Class.
    You need to extends the RecyclerView.Adapter.

    package com.coderzheaven.reyclerviewexample;
    
    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.squareup.picasso.Picasso;
    
    import java.util.List;
    
    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyCustomViewHolder> {
    
        private List<ListItem> listItems;
        private Context mContext;
    
        public MyRecyclerAdapter(Context context, List<ListItem> listItems) {
            this.listItems = listItems;
            this.mContext = context;
        }
    
        @Override
        public MyCustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
            MyCustomViewHolder vh = new MyCustomViewHolder(view);
            return vh;
            
        }
    
        @Override
        public void onBindViewHolder(MyCustomViewHolder customViewHolder, int position) {
    
            ListItem listItem = listItems.get(position);
    
            //Download image using picasso library and set Thumbnail
            Picasso.with(mContext).load(listItem.getThumbnail())
                    .error(android.R.color.holo_red_light)
                    .placeholder(R.drawable.no_image)
                    .into(customViewHolder.imageView);
    
            //Set title
            customViewHolder.textView.setText(listItem.getTitle());
        }
    
        @Override
        public int getItemCount() {
            return (null != listItems ? listItems.size() : 0);
        }
    }
    

    This is the CustomView for each row in the RecyclerView.

    package com.coderzheaven.reyclerviewexample;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyCustomViewHolder extends RecyclerView.ViewHolder {
    
        protected ImageView imageView;
        protected TextView textView;
    
        public MyCustomViewHolder(View view) {
            super(view);
            this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
            this.textView = (TextView) view.findViewById(R.id.title);
        }
    
    }
    

Handling Row Click Events in RecyclerView

Unlike Listviews, there are no ItemClick listeners for RecyclerViews.
So we need to implement a Gesture listener for the Recycler view and find the ChildView based on X and Y by implementing RecyclerView.OnItemTouchListener and pass our interface listener these values.
Lets see how we can implement this.

You need to create a separate class for that and name it “MyRecyclerItemClickListener.java”.

package com.coderzheaven.reyclerviewexample;

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

public class MyRecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;

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

    GestureDetector mGestureDetector;

    public MyRecyclerItemClickListener(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){

    }
}

Now apply this to out RecyclerView like this

mRecyclerView.addOnItemTouchListener(
                new MyRecyclerItemClickListener(this, new MyRecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Log.i(TAG, "Clicked Item Position : " + position);
                    }
                })
        );

Done.

You can download the Android Studio Source Code from here.

Leave a Reply

Your email address will not be published. Required fields are marked *