Simple Android Recyclerview Example

Simple Android RecyclerView example

The following is a minimal example that will look like the following image.

RecyclerView with a list of animal names

Start with an empty activity. You will perform the following tasks to add the RecyclerView. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the RecyclerView row
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

You can update the version numbers to whatever is the most current. Use compile rather than implementation if you are still using Android Studio 2.x.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
android:id="@+id/rvAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>

Create row layout

Each row in our RecyclerView is only going to have a single TextView. Create a new layout resource file.

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="wrap_content"
android:orientation="horizontal"
android:padding="10dp">

<TextView
android:id="@+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each row with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;

// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}

// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}

// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}

// total number of rows
@Override
public int getItemCount() {
return mData.size();
}


// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;

ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}

@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}

// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}

// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}

// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the rows. This was available in the old ListViews and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

MyRecyclerViewAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");

// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}

@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle row click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Adding a divider between rows

You can add a simple divider like this

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

If you want something a little more complex, see the following answers:

  • How to add dividers and spaces between items in RecyclerView?
  • How to indent the divider in a linear layout RecyclerView (ie, add padding, margin, or an inset only to the ItemDecoration)

Changing row color on click

See this answer for how to change the background color and add the Ripple Effect when a row is clicked.

Insert single item

Updating rows

See this answer for how to add, remove, and update rows.

Insert single item

Further reading

  • CodePath
  • YouTube tutorials
  • Android RecyclerView Example (stacktips tutorial)
  • RecyclerView in Android: Tutorial

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Short answer

For those who are already familiar with setting up a RecyclerView to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

If you need more help than that, then check out the following example.

Full example

The following is a minimal example that will look like the image below.

Sample Image

Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the grid cell
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
android:id="@+id/rvNumbers"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:padding="5dp"
android:layout_width="50dp"
android:layout_height="50dp">

<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

private String[] mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;

// data is passed into the constructor
MyRecyclerViewAdapter(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}

// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}

// binds the data to the TextView in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.myTextView.setText(mData[position]);
}

// total number of cells
@Override
public int getItemCount() {
return mData.length;
}


// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;

ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.info_text);
itemView.setOnClickListener(this);
}

@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}

// convenience method for getting data at click position
String getItem(int id) {
return mData[id];
}

// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}

// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

MyRecyclerViewAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// data to populate the RecyclerView with
String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvNumbers);
int numberOfColumns = 6;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}

@Override
public void onItemClick(View view, int position) {
Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
}
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Rounded corners

  • Use a CardView

Auto-fitting columns

  • GridLayoutManager - how to auto fit columns?

Further study

  • Android RecyclerView with GridView GridLayoutManager example tutorial
  • Android RecyclerView Grid Layout Example
  • Learn RecyclerView With an Example in Android
  • RecyclerView: Grid with header
  • Android GridLayoutManager with RecyclerView in Material Design
  • Getting Started With RecyclerView and CardView on Android

How do I use a RecyclerView

Recyclerview:

Recycler view is same as listview but recyclerview is added in android support lib for material design concept.

Example:

Add dependency for recyclerview

compile 'com.android.support:recyclerview-v7:23.1.0'

Add recyclerview in main layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/item_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</LinearLayout>

Make one item layout xml file (here is ur item file)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/txtChords"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/txtLyrics"/>

</LinearLayout>

Make one model class for each item in list.it can be any custom class.

public class Item {

private String name;

public Item(String n) {
name = n;
}
public String getName() {
return name;
}

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

Now most important part is to make adapter for recyclerview:

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.codexpedia.list.viewholder.R;
import java.util.ArrayList;


public class ItemArrayAdapter extends RecyclerView.Adapter<ItemArrayAdapter.ViewHolder> {

//All methods in this adapter are required for a bare minimum recyclerview adapter
private int listItemLayout;
private ArrayList<Item> itemList;
// Constructor of the class
public ItemArrayAdapter(int layoutId, ArrayList<Item> itemList) {
listItemLayout = layoutId;
this.itemList = itemList;
}

// get the size of the list
@Override
public int getItemCount() {
return itemList == null ? 0 : itemList.size();
}


// specify the row layout file and click for each row
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(listItemLayout, parent, false);
ViewHolder myViewHolder = new ViewHolder(view);
return myViewHolder;
}

// load data in each row element
@Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView item = holder.item;
item.setText(itemList.get(listPosition).getName());
}

// Static inner class to initialize the views of rows
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
item = (TextView) itemView.findViewById(R.id.txtChords);
}
@Override
public void onClick(View view) {
Log.d("onclick", "onClick " + getLayoutPosition() + " " + item.getText());
}
}

This is simple adapter with minimum requirement method.

Now bind adapter with recyclerview

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.codexpedia.list.viewholder.R;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initializing list view with the custom adapter
ArrayList <Item> itemList = new ArrayList<Item>();

ItemArrayAdapter itemArrayAdapter = new ItemArrayAdapter(R.layout.list_item, itemList);
recyclerView = (RecyclerView) findViewById(R.id.item_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(itemArrayAdapter);

// Populating list items
for(int i=0; i<100; i++) {
itemList.add(new Item("Item " + i));
}

}

}

Hope this example will help u...
You can ask any question if u have any confusion.

You can refer this link if u want to make complex list

https://www.binpress.com/tutorial/android-l-recyclerview-and-cardview-tutorial/156

What the best way to creat Expandable Recyclerview Android/Java?

implementation 'com.github.cachapa:ExpandableLayout:2.9.2'

try this I'm using this library currently inside the app that I'm working on, it's simple easy to use and works fine, let me know if you try it !!

How to build a horizontal ListView with RecyclerView

Is there a better way to implement this now with RecyclerView now?

Yes.

When you use a RecyclerView, you need to specify a LayoutManager that is responsible for laying out each item in the view. The LinearLayoutManager allows you to specify an orientation, just like a normal LinearLayout would.

To create a horizontal list with RecyclerView, you might do something like this:

LinearLayoutManager layoutManager
= new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false);

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

Is there any simple implementation or tutorial to implement RecyclerView in android?

RecyclerView Adapter Example:

  1. Adapter issue can be solved using below code:

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

    private final Context mContext;
    private List<String> mData1, mData2;

    public MyAdapter(Context mContext, String[] data1, String[] data2) {
    this.mContext = mContext;
    if (data1 != null)
    mData1 = new ArrayList<String>(Arrays.asList(data1));
    else
    mData1 = new ArrayList<String>();

    if (data2 != null)
    mData2 = new ArrayList<String>(Arrays.asList(data2));
    else
    mData2 = new ArrayList<String>();
    }

    public void add(String s, int position) {
    position = position == -1 ? getItemCount() : position;
    mData1.add(position, s);

    notifyItemInserted(position);
    }

    public void remove(int position) {
    if (position < getItemCount()) {
    mData1.remove(position);
    notifyItemRemoved(position);
    }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
    View itemView = inflater.inflate(R.layout.list_item, viewGroup, false);

    return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder myViewHolder, final int position) {
    myViewHolder.tv1.setText(mData1.get(position));
    myViewHolder.tv2.setText(mData2.get(position));
    myViewHolder.itemView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    clickListener.onClick(v, position);
    }
    });
    }

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

    ClickListener clickListener;

    public void setClickListener(ClickListener clickListener) {
    this.clickListener = clickListener;
    }

    public interface ClickListener {
    public void onClick(View v, int pos);

    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
    protected TextView tv1;
    protected TextView tv2;

    public MyViewHolder(View itemView) {
    super(itemView);
    tv1 = (TextView) itemView.findViewById(R.id.txt1);
    tv2 = (TextView) itemView.findViewById(R.id.txt2);

    }

    }
    }

Usage is as below:

MyAdapter adapter=....;
adapter.setClickListener(new ClickListener() {

@Override
public void onClick(View v, int pos) {
// do whatever you want
}
});

  1. There is not any Simple way to do that. But i would suggest you one workaround for this. Add below view as a divider at the bottom inside your list_item.xml.

     <View
    android:layout_width="wrap_content"
    android:layout_height="0.5dip"
    android:background="@color/light_gray"/>
  2. Item click listener is also resolved in point no. 1 above.

I hope this would help you.



Related Topics



Leave a reply



Submit