Recycler View in Android

Introduction:
      
       Android Lollipop is highly focused on rich user experience and what they called it as material design. here we will take a look at the new UI widget called RecyclerView. RecyclerView its a replacement of existing ListView widget .  

       RecyclerView is more advanced and flexible and efficient version of ListView. RecyclerView ViewGroup is an container for larger data set of views that can be recycled and scrolled very efficiently. RecyclerView can be used for larger datasets to be rendered on the UI like a list. RecyclerView provides maximum flexibility to design different kind of views.

Screenshots:








Using this code:

1. Create new project in Android Studio

    Create a new Android application in Android Studio IDE and add the support library dependency.

2. Adding support library
  
    
   Android SDK doesn’t includes the RecyclerView class, and hence for using RecyclerView in your project you first need to add the recycler view support library to your project. Android Studio users can add the following graddle dependency to project build.graddle file. 

dependencies 
{
        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'
}


1. First create RecyclerView in xml.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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:fitsSystemWindows="true"
    tools:context="kalidoss.com.recyclerview.MainActivity">
    
    <android.support.design.widget.AppBarLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:theme="@style/AppTheme.AppBarOverlay">
    
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>
    
    </android.support.design.widget.AppBarLayout>
    
  <include layout="@layout/content_main"/>
    
</android.support.design.widget.CoordinatorLayout>


content_main.xml
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        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="kalidoss.com.recyclerview.MainActivity"
        tools:showIn="@layout/activity_main">
    
      <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:longClickable="true"/>

 </RelativeLayout>

here is the design layout for recyclerView row 
recyclerview_row.xml
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="horizontal"
     android:paddingBottom="10dp"
     android:paddingTop="10dp"
     android:background="?android:attr/selectableItemBackground">
    
    <TextView
        android:id="@+id/contact_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    
    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_launcher"
        android:id="@+id/imageView"/>
 </LinearLayout>

       Here, i am going to load some datas to recyclerView, and add setOnItemClickListner to recyclerView.   by using interface in adapter class to call recyclerViewAdapter.setOnItemClickListner in MainActivity.java

MainActivity.java
package kalidoss.com.recyclerview;
    
    import android.content.Context;
    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 android.view.View;
    import android.widget.Toast;
    
    /**
     * Created by Kalidoss on 28/01/16.
     */
    
    public class MainActivity extends AppCompatActivity {
        
        RecyclerView recyclerView;
        RecyclerViewAdapter recyclerViewAdapter;
        Model model;
        Context context;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context = this;
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            addValues();
            recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
            recyclerViewAdapter = new RecyclerViewAdapter(context);
            
            final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(recyclerViewAdapter);
            recyclerView.isAnimating();
           
            // recyclerView divider line
            recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
            
            recyclerViewAdapter.setOnItemClickListener
                                  (new RecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View itemView, int position) {
                    
                    String name = Singleton.getInstance().modelList.get(position).getName();
                    Toast.makeText(context, name + " was clicked!", Toast.LENGTH_SHORT).show();
                }
            });
        }
        
      public void addValues() {
            model = new Model();
            model.setName("Kalidoss");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("RJ");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Tamil");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Kd");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Hari");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Sampath");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Mani");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Sheik");
            Singleton.getInstance().modelList.add(model);
            
            model = new Model();
            model.setName("Niyas");
            Singleton.getInstance().modelList.add(model);
        }
  }

 then using Model POJO class to parse the datas. Create a new class Model.java class in our project.

Model.java
package kalidoss.com.recyclerview;
    
    /**
     * Created by Kalidoss on 17/02/16.
     */

 public class Model {
         
     public String name;

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

       The Singleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.   

Singleton.java
   package kalidoss.com.recyclerview;
    
   import java.util.ArrayList;
    
    /**
     * Created by Kalidoss on 28/01/16.
     */

    public class Singleton {
        
        private static volatile Singleton instance = null;
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    // Double check
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
        public ArrayList<Model> modelList = new ArrayList<Model>();
    }


Android RecyclerView includes special kind of adapter which works pretty much same as traditional Android adapters but with additional functionalities. The additional functionalities includes;
  adds two new methods  like onCreateViewHolder() and onBindViewHolder()to organize the code. You must override these two methods for inflate the view and to bind data to the view.
  Implements ViewHolder default.Conceptually RecyclerView.ViewHolderworks same as the ViewHolder design pattern which we have been using with other Adapters.
Takes care of the overhead of recycling and gives better performance and scrolling.
RecyclerViewAdapter.java 

package kalidoss.com.recyclerview;

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


/**
* Created by Kalidoss on 17/02/16.
*/

public class RecyclerViewAdapter extends                                              RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>  {
    
    Context mContext;
    
    // Define listener member variable
    private static OnItemClickListener listener;
    
    // Define the listener interface
    public interface OnItemClickListener {
    void onItemClick(View itemView, int position);
    }
    
    // Define the method that allows the parent activity or fragment to define the listener
    public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
    }
    
    public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView txtName;
    
    public MyViewHolder(View view) {
    super(view);
    txtName = (TextView) view.findViewById(R.id.contact_name);
    
    itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         // Triggers click upwards to the adapter on click
         if (listener != null)
         listener.onItemClick(itemView, getLayoutPosition());
         }
      });
     }
    }
    
    public RecyclerViewAdapter(Context context) {
    this.mContext = context;
    }
    
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
    .inflate(R.layout.recyclerview_row, parent, false);
    return new MyViewHolder(itemView);
    }
    
    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
    holder.txtName.setText(Singleton.getInstance().modelList.get(position).getName());
    }
    
    @Override
    public int getItemCount() {
    return Singleton.getInstance().modelList.size();
    }

}


3. Add divider line in recyclerView

    to define ItemDecoration for the RecyclerView is as following

SimpleDividerItemDecoration.java 
package kalidoss.com.recyclerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
* Created by Kalidoss on 18/02/16.
*/

public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;

public SimpleDividerItemDecoration(Context context) {
mDivider= ContextCompat.getDrawable(context, R.drawable.line_divider);
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
  int left = parent.getPaddingLeft();
  int right = parent.getWidth() - parent.getPaddingRight();

  int childCount = parent.getChildCount();
  for (int i = 0; i < childCount; i++) {
  View child = parent.getChildAt(i);

  RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

  int top = child.getBottom() + params.bottomMargin;
  int bottom = top + mDivider.getIntrinsicHeight();
  mDivider.setBounds(left, top, right, bottom);
  mDivider.draw(c);
  }
 }
}

Finally set like this in activity

recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));

add line_divider.xml in drawable folder

line_divider.xml
<?xml version="1.0" encoding="utf-8"?>
    android:shape="rectangle">
    
    <size
    android:width="1dp"
    android:height="1dp" />
    
    <solid android:color="#d3d3d3" />
    
</shape>


Happy Coding....
Previous
Next Post »