Recycler View in Android

In this article we will discuss how to use the recycler view in android.

Introduction:

Recycler View is introduced in Marshmallow. It is an advanced version of the List View and Grid View with improved performance and other benefits. Recycler view simplifies the display and handling of a large set of data.

Steps for implement Recycler view:

First of all, decide how you want the data to be shown in the list or in the grid. You will be able to use one of the Recycler View library’s standard layout managers.

Design how each element in the list is going to look and behave. Based on this design, extend the View Holder class. Your version of View Holder provides all the functionality for your list items. Your view holder is a wrapper around a View, and that view is managed by Recycler View.

Define the Adapter that associates your data with the View Holder views.

When you define adapter, you need to override three key methods:

onCreateViewHolder(): Recycler View calls this method whenever it needs to create a new View Holder. The method creates and initialise the View Holder .

onBindViewHolder(): Recycler View calls this method to associate a View Holder with data. The method gets the data and uses the data to fill in the view holder’s layout. For example, if the Recycler View displays a list of names, the method finds the name in the list and fills in the view holder’s Text View.

getItemCount(): Recycler View calls this method to get the size of the data set. Recycler View uses this to determine when there are no more items that can be displayed.

Example of Recycler view:

Add android Recycler view into activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:context=".MainActivity"/>

Create a custom layout list_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightLarge"
android:background="@drawable/border">

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:contentDescription="Icon" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toEndOf="@id/imageView"
android:layout_toRightOf="@id/imageView"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>

Create a border.xml file in the drawable directory which is used in items of RecyclerView.

border.xml

<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android"  
android:shape="rectangle">  
 	 <solid android:color="#FFFFFF" />  
 	<stroke  
android:width="1dp"  
android:color="#CCCCCC" />  
</shape>  

Create a MyListData.java class with the following code. This class is used as (POJO) class which sets the properties of the items.

MyListData.java

package example.com.recyclerviewlist;  
public class MyListData{  
 private String description;  
 private int imgId;  
 public MyListData(String description, int imgId) {  
 	this.description = description;  
  	this.imgId = imgId;  
 }  
 public String getDescription() {  
 return description;  
 }  
 public void setDescription(String description) {  
this.description = description;  
  }  
 public int getImgId() {  
  	return imgId;  
  }  
public void setImgId(int imgId) {  
 this.imgId = imgId;  
  }  
}  

Create a MyListAdapter.java class. This class extends RecyclerView.Adapter class and overrides its unimplemented methods. The onCreateViewHolder() method inflates the list_item.xml. In the onBindViewHolder() method each data item is set to each row.

MyListAdapter.java

package examplet.com.recyclerviewlist;    
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.RelativeLayout;  
import android.widget.TextView;  
import android.widget.Toast;  
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder>{  
 private MyListData[] listdata;    
   // RecyclerView recyclerView;  
  public MyListAdapter(MyListData[] listdata) {  
       this.listdata = listdata;  
   }  
@Override  
   public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
  LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());  
 View listItem= layoutInflater.inflate(R.layout.list_item, parent, false);  
ViewHolder viewHolder = new ViewHolder(listItem);  
   return viewHolder;  
  }  
    @Override  
 public void onBindViewHolder(ViewHolder holder, int position) {  
  final MyListData myListData = listdata[position];  
 holder.textView.setText(listdata[position].getDescription());  
  holder.imageView.setImageResource(listdata[position].getImgId());  
   holder.relativeLayout.setOnClickListener(new View.OnClickListener() {  
   @Override  
 public void onClick(View view) {  
                Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();  
            }  
        });  
    }
    @Override  
public int getItemCount() {  
       	 return listdata.length;  
    	}    
 public static class ViewHolder extends RecyclerView.ViewHolder {  
 public ImageView imageView;  
  public TextView textView;  
  public RelativeLayout relativeLayout;  
 public ViewHolder(View itemView) {  
 super(itemView);  
 this.imageView = (ImageView) itemView.findViewById(R.id.imageView);  
   this.textView = (TextView) itemView.findViewById(R.id.textView);  
    relativeLayout = (RelativeLayout)itemView.findViewById(R.id.relativeLayout);  }  
}  
}  

Finally, in the MainActivity.java class, add the following code. This class creates the array of items for My List Data class and sets the adapter class to Recycler View.

MainActivity.java

package example.com.recyclerviewlist;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.support.v7.widget.LinearLayoutManager;  
import android.support.v7.widget.RecyclerView;    
public class MainActivity extends AppCompatActivity {  
  @Override  
 protected void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 setContentView(R.layout.activity_main);  
 MyListData[] myListData = new MyListData[] {  
 new MyListData("Email", android.R.drawable.ic_dialog_email),  
              new MyListData("Info", android.R.drawable.ic_dialog_info),  
 new MyListData("Delete", android.R.drawable.ic_delete),  
 new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),  
 new MyListData("Alert", android.R.drawable.ic_dialog_alert),  
 new MyListData("Map", android.R.drawable.ic_dialog_map),  
new MyListData("Email", android.R.drawable.ic_dialog_email),  
 new MyListData("Info", android.R.drawable.ic_dialog_info),  
  new MyListData("Delete", android.R.drawable.ic_delete),  
 new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),  
 new MyListData("Alert", android.R.drawable.ic_dialog_alert),  
 new MyListData("Map", android.R.drawable.ic_dialog_map),  
 };  
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);  
 MyListAdapter adapter = new MyListAdapter(myListData);  
 recyclerView.setHasFixedSize(true);  
 recyclerView.setLayoutManager(new LinearLayoutManager(this));  
 recyclerView.setAdapter(adapter);  
  }  
}  

 

 

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories