Simple Recyclerview Example in Android

Let’s create a simple recyclerview example in android studio and clear basic concepts. Recycler view is one of the most useful features nowadays in android.

What is Recyclerview?

Recycler view is the advance version of the list view. Before recycler view came people were using the list view. Most of the disadvantages of list views are solved by using Recyclerview.
By using List View the only type of view available was the vertical Listview and there is no official way to even implement a horizontal ListView whereas now by using recycler view we can have
1.) LinearLayoutManager
2.) StaggeredLayoutManager
3.) GridLayoutManager

Difference between ListView and Recyclerview?

ListView is a good old widget that has been included in the Android SDK since API 1.Until Android Lollipop’s release, we mostly used this and it wasn’t that bad – the API is mostly built-in. Moreover, the ListView class is a bit too-heavy it has many responsibilities.

While Recyclerview is easy to use and also it is very comfortable to use and can be scrolled smoothly.

The major difference between the Listview and Recycler view is that while using a list view the whole data is loaded at the time when an application has started.

This results in the application taking more time to load the data.

Whereas using Recyclerview the data is loaded while scrolling so automatically the loading time of the application decreases.
So we can say that the Recyclerview is more appropriate to use than ListView.

Here we would see an example in which by clicking on the recycler view we can get the position of it. As shown below

First, we would start with a Simple Recyclerview Example in Android:

The First step is to add the Design and Recyclerview Library :

Add design and recycler view libraries in build.Gradle file

implementation 'com.android.support:design:23.1.1'
implementation 'com.android.support:recyclerview-v7:23.1.1'                                 

The second step is in your activity_main take one Imageview, One Simple TextView, and three buttons. The code for it is given below

<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"
    tools:context=".Activity.MainActivity">

<ImageView
    android:id="@+id/imglogo"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:scaleType="fitXY"
    android:padding="20dp"
    android:src="@drawable/logo"/>

   <TextView
       android:id="@+id/txt"
       android:layout_below="@id/imglogo"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@string/recyclerview"
       android:layout_marginLeft="10dp"
       android:gravity="center"
       android:layout_marginRight="10dp"
       android:padding="10dp"
       android:textColor="@android:color/black"
       android:textSize="18dp"/>

   <Button
       android:id="@+id/btnsimple"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/txt"
       android:layout_marginTop="10dp"
       android:text="@string/simple"
       android:layout_marginLeft="20dp"
       android:layout_marginRight="20dp"
       android:elevation="2dp"
       android:background="@drawable/roundcorners"
       android:backgroundTint="@color/background"/>

   <Button
       android:id="@+id/btncustom"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/btnsimple"
       android:layout_marginTop="20dp"
       android:text="@string/custom"
       android:layout_marginLeft="20dp"
       android:layout_marginRight="20dp"
       android:elevation="2dp"
       android:background="@drawable/roundcorners"
       android:backgroundTint="@color/background"/>

   <Button
       android:id="@+id/btngrid"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/btncustom"
       android:layout_marginTop="20dp"
       android:text="@string/grid"
       android:layout_marginLeft="20dp"
       android:layout_marginRight="20dp"
       android:elevation="2dp"
       android:background="@drawable/roundcorners"
       android:backgroundTint="@color/background"/>
</RelativeLayout>

home

Now the fourth step is in the MainActivity.java file declares all the views and allocates memory to it. The code for it is

Button btnsimple , btncustom , btngrid;
btnsimple = findViewById(R.id.btnsimple);
btncustom = findViewById(R.id.btncustom);
btngrid = findViewById(R.id.btngrid);

The Next Step is Create a new Activity by Right-Clicking on app->New->Activity->Empty Activity and name it as SimpleActivity.

Now in activity_simple.xml add one Recyclerview. As shown below.

<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"
    tools:context=".Activity.SimpleActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/item_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"/>

</RelativeLayout>

Now in SimpleActivity.java add view and initialize it.

RecyclerView recyclerView;
recyclerView = findViewById(R.id.item_list);

Then create the raw file by Right-clicking on layout->new->layout Resource File. And name it as list_item.xml.
The raw file contains a view that you want to repeat for all the items.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
      <TextView
        android:id="@+id/row"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
       />
</RelativeLayout>

Now create the adapter by right-clicking on java folder java->new->java class. And name it as ItemArrayAdapter.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rdm.simplerecyclerview.R;
import com.rdm.simplerecyclerview.Activity.SimpleActivity;

import java.util.ArrayList;

public class ItemArrayAdapter extends RecyclerView.Adapter<ItemArrayAdapter.ViewHolder> {
    private ArrayList<String> heros;
    Context context;

    public ItemArrayAdapter(SimpleActivity simpleActivity, ArrayList heros) {
        this.context = simpleActivity;
        this.heros = heros;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        ViewHolder myViewHolder = new ViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.item1.setText(heros.get(position)+"");
        viewHolder.item1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, viewHolder.item1.getText().toString()+"  index is "+position, Toast.LENGTH_SHORT).show();
            }
        });

    }
    @Override
    public int getItemCount() {
        return heros == null ? 0 : heros.size();
    }
    static class ViewHolder extends RecyclerView.ViewHolder  {
        public TextView item1;
        public ViewHolder(View itemView) {
            super(itemView);
            item1 =  itemView.findViewById(R.id.row);
        }

    }
}

Then in the SimpleActivity.java class do the following coding. Here is the full code of SimpleActivity.java file.

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.rdm.simplerecyclerview.Adapter.ItemArrayAdapter;
import com.rdm.simplerecyclerview.R;

import java.util.ArrayList;

public class SimpleActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    private ArrayList heros;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple);

        recyclerView = findViewById(R.id.item_list);
        recyclerView.setLayoutManager(new GridLayoutManager(SimpleActivity.this,1));
        heros = new ArrayList<>();
        heros.add("Vin Diesel");
        heros.add(" Matt Damon");
        heros.add(" Richard Gere");
        heros.add(" Clive Owen");
        heros.add(" Mel Gibson");
        heros.add(" George Clooney");
        heros.add(" Jack Nicholson");
        heros.add(" Tom Hardy");
        heros.add(" Robert Downey Jr.");
        heros.add(" Orlando Bloom");
        heros.add(" Ian McKellen");
        heros.add(" Antonio Banderas");
        heros.add(" Guy Pearce");
        heros.add(" Samuel L. Jackson");
        heros.add(" Gerard Butler");
        ItemArrayAdapter adapter = new ItemArrayAdapter(SimpleActivity.this,heros);
        recyclerView.setAdapter(adapter);
    }
}

Then in MainActivity.java add the button Onclick event.

btnsimple.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, SimpleActivity.class);
        startActivity(intent);
    }
});

Now you can run this app and can see how it works!!!

simple

simple1

Now let’s go to one step higher that is, Let’s create a Custom Recyclerview

For this first, we have to add a Card View Library in build.Gradle file

implementation 'com.android.support:cardview-v7:23.1.1'

Now again create a new activity as we have created before and name it as CustomActivity.

Then in activity_custom.xml add one recycler view in it

<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"
    tools:context=".Activity.CustomActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:id="@+id/customrecyclerview"/>

</RelativeLayout>

Now create one another layout resource file and name it as custom_list_item and edit it as you want the view design to repeat. Here we have added one CardView and one TextView

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

    <androidx.cardview.widget.CardView
        android:id="@+id/card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp">

        <TextView
            android:id="@+id/tv_country"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_gravity="center"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>



    </androidx.cardview.widget.CardView>
</LinearLayout>

In the next step create a new java class that is the adapter and name it as Custom_Adapter.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rdm.simplerecyclerview.Activity.CustomActivity;
import com.rdm.simplerecyclerview.R;

import java.util.ArrayList;

public class Custom_Adapter extends RecyclerView.Adapter<Custom_Adapter.ViewHolder> {
    private ArrayList<String> countries;
    Context context ;

    public Custom_Adapter(CustomActivity customActivity, ArrayList<String> countries) {
        this.context = customActivity;
        this.countries = countries;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.tv_country.setText(countries.get(position));
        viewHolder.tv_country.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context,  holder.tv_country.getText().toString()+"  index is "+position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return countries.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_country;
        public ViewHolder(View view) {
            super(view);

            tv_country = view.findViewById(R.id.tv_country);
        }
    }
}

Now edit the CustomActivity.java file as below.

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.rdm.simplerecyclerview.Adapter.Custom_Adapter;
import com.rdm.simplerecyclerview.R;

import java.util.ArrayList;

public class CustomActivity extends AppCompatActivity {
    private ArrayList countries;
    RecyclerView customrecyclerview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);
        customrecyclerview = findViewById(R.id.customrecyclerview);
        customrecyclerview.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        customrecyclerview.setLayoutManager(layoutManager);
        countries = new ArrayList<>();
        countries.add("Europe");
        countries.add("China");
        countries.add("Maxico");
        countries.add("Phillipines");
        countries.add("Turkey");
        countries.add("United Kingdom");
        countries.add("Italy");
        countries.add("Ukraine");
        countries.add("Australia");
        countries.add("India");
        countries.add("United States of America");
        countries.add("Germany");
        countries.add("Russia");
        countries.add("Canada");
        countries.add("Afghanisthan");
        countries.add("Malaysia");
        countries.add("Nepal");
        countries.add("Srilanka");

        Custom_Adapter adapter = new Custom_Adapter(CustomActivity.this, countries);
        customrecyclerview.setAdapter(adapter);
    }
}

Now in MainActivity.java add second buttons Onclick event.

btnsimple.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, SimpleActivity.class);
        startActivity(intent);
    }
});
btncustom.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, CustomActivity.class);
        startActivity(intent);
    }
});

Simple Recyclerview Example in Android

Simple Recyclerview Example in Android

That’s it now your custom Recyclerview is Ready you can check it.

Therefore Let’s go one step more ahead so let’s create a Grid Recyclerview

Now, what is grid Recyclerview the question would come in your mind?

So the grid Recyclerview is a format like a table.
Let’s see how to create it.

For it again creates a new activity and names it as GridActivity

Now in it activity_grid.xml add recycler view.

<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"
    tools:context=".Activity.GridActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rec_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"/>

</RelativeLayout>

Then create a new layout resource file name it as grid_list_item.xml

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

    <androidx.cardview.widget.CardView
        android:id="@+id/cardgrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp">

    <TextView
        android:id="@+id/country"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_gravity="center"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    </androidx.cardview.widget.CardView>

</LinearLayout>

Similarly, create a new java class that is adapter and name it as Grid_Adapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rdm.simplerecyclerview.Activity.GridActivity;
import com.rdm.simplerecyclerview.R;

import java.util.ArrayList;

public class Grid_Adapter extends RecyclerView.Adapter {
    private ArrayList<String> flowers;
    Context context;

    public Grid_Adapter(GridActivity gridActivity, ArrayList<String> countryname) {
        this.flowers = countryname;
        this.context = gridActivity;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
       final ViewHolder viewHolder = (ViewHolder) holder;
       viewHolder.text.setText(flowers.get(position));
       viewHolder.text.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Toast.makeText(context, viewHolder.text.getText().toString()+"  index is "+position, Toast.LENGTH_SHORT).show();
           }
       });

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView text;
        public ViewHolder(View view) {
            super(view);

            text = view.findViewById(R.id.country);
        }
    }
}

Now edit the GridActivity.java file

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.rdm.simplerecyclerview.Adapter.Grid_Adapter;
import com.rdm.simplerecyclerview.R;

import java.util.ArrayList;

public class GridActivity extends AppCompatActivity {
    RecyclerView rec_grid;
    private ArrayList flowers;

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

        rec_grid = findViewById(R.id.rec_grid);
        rec_grid.setLayoutManager(new GridLayoutManager(GridActivity.this,2));
        flowers = new ArrayList<>();
        flowers.add("Rose");
        flowers.add("Lotus");
        flowers.add("Mogra");
        flowers.add("Tulips");
        flowers.add("Orchids");
        flowers.add("Sunflower");
        flowers.add("Lilies");
        flowers.add("Daffodils");
        flowers.add("Marigold");
        flowers.add("Dahlia");
        flowers.add("Gladioli");
        flowers.add("Carnations");
        flowers.add("Chrysanthemums");
        flowers.add("Apple blossom");
        flowers.add("Camellia");
        flowers.add(" Iris");
        flowers.add("Lilac");
        flowers.add("Peony");
        flowers.add("Sweet pea");
        flowers.add("Magnolia");
        flowers.add("Lavender");
        flowers.add("Ranunculus");
        flowers.add("Stock");
        flowers.add("Statice");
        flowers.add("Proteas");
        flowers.add("Queen Anne’s Lace");
        flowers.add("Poinsettia");
        flowers.add("Snapdragons");
        flowers.add("Lisianthus");
        flowers.add("Freesia");
        flowers.add(" Delphinium");
        flowers.add("Bourvardia");
        flowers.add("Daisies");
      Grid_Adapter adapter = new Grid_Adapter(GridActivity.this,flowers);
        rec_grid.setAdapter(adapter);

    }
}

Finally, edit the MainActivity.java that is adding the third button’s Onclick event.

btnsimple.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, SimpleActivity.class);
        startActivity(intent);
    }
});
btncustom.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, CustomActivity.class);
        startActivity(intent);
    }
});

btngrid.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, GridActivity.class);
        startActivity(intent);
    }
});

Simple Recyclerview Example in Android

grid1

Now the whole code of MainActivity is as below

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.rdm.simplerecyclerview.R;

public class MainActivity extends AppCompatActivity {

    Button btnsimple , btncustom , btngrid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Viewinitializing();

        btnsimple.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SimpleActivity.class);
                startActivity(intent);
            }
        });
        btncustom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, CustomActivity.class);
                startActivity(intent);
            }
        });

        btngrid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, GridActivity.class);
                startActivity(intent);
            }
        });
    }

    private void Viewinitializing() {
        btnsimple = findViewById(R.id.btnsimple);
        btncustom = findViewById(R.id.btncustom);
        btngrid = findViewById(R.id.btngrid);
    }
}

That’s it your application is ready…

You can download the full source code from here…

Conclusion:

Hope you understand the concept of recycler view with simple recyclerview Example in Android and for more such examples visit androidcrown.com
For any query do comment in the below section.

8 Replies to “Simple Recyclerview Example in Android”

  1. you are really a good webmaster. The web site loading speed is amazing. It sort of feels that you are doing any unique trick. Also, The contents are masterpiece. you have done a excellent activity on this matter!|

  2. Excellent post. I was checking continuously this weblog and I’m inspired! Extremely useful info specially the final phase 🙂 I maintain such info much. I used to be looking for this particular information for a very lengthy time. Thank you and best of luck. |

  3. We’re a group of volunteers and starting a new scheme in our community. Your website provided us with valuable information to work on. You have done a formidable job and our entire community will be thankful to you.|

Leave a Reply

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