recycler view in android

Recycler View in Android

In this post, we are going to learn about the recycler view in android studio. As the name suggests Recycler view is based on the principle of recycling.

Recycler view used a layout as view and create multiple of that view according to need.

For Example, If you have only one item in the list then the Recycler view generates only one copy and when you need more than one recycler view to generate multiple views.

Let’s see example of Recycler View

Table of Content

  1. Creating Layout For recycler view in android studio
  2. Adding recycler view in the activity .xml file
  3. Creating a Recycler view adapter
  4. Merge adapter with activity to show Recycler View
  5. Result

Creating Layout For Recycler View in android

We create a layout for the recycler view, Layout is simply a combination of view which we want to show.

Go To -> File

Then -> New

And Then -> Layout Resource File

Name it as activity_cart_recycler.xml and edit it look like this.


<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_margin="3dp"
    android:orientation="vertical"
    android:elevation="5dp"
    app:cardBackgroundColor="FFFFC107"
    android:layout_height="wrap_content">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_margin="2dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:text="Name"
        android:layout_alignParentStart="true"
        android:textColor="#FFFFFF"
        android:id="@+id/textView"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFF"
            android:id="@+id/price"
            android:layout_margin="2dp"
            android:layout_alignParentEnd="true"
            android:text="Total Price"/>


    </RelativeLayout>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="      *    Name"
            android:layout_margin="2dp"
            android:textColor="#FFFFFF"
            android:id="@+id/quantity"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >


        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:layout_alignParentEnd="true"
            android:textColor="#FFFFFF"
            android:background="@drawable/ic_delete_sweep_black_24dp"
            android:id="@+id/closeImage"/>

    </RelativeLayout>
    </LinearLayout>


</androidx.cardview.widget.CardView>

After you write this code You see something like this

Adding Recycler View in activity.xml

After creating Recycler view, we are going to add recycler view in .xml

Goto Design section of your activity.xml file

From Palette Search Recycler View

Pick and drop recycler view from palette to app, Now it take’s some time to resolve dependency and add recycler view to your activity.xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="FFFFC107"
    android:layout_height="match_parent"
    tools:context=".Activity.CartActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <androidx.appcompat.widget.Toolbar
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:id="@+id/toolbar"
                    app:title="Cart "
                    android:background="FFFFC107"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>


       
        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#FFFFFF"
            android:id="@+id/recycler_cart_view"
            />

</LinearLayout>

Now, we successful added recycler view in activity.xml

Creating a Recycler View adapter

After adding recycler view, We need to connect our recycler view layout to activity.xml through adapter. Adapter act as bridge between recycler view and activity.xml

Adapter bind the data recieved from activity.xml to recycler view.

Go To -> New

Then -> New Java Class

Name it CartRecycler

package com.piyushjaiswal121.demo.Adapter;

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

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

import com.piyushjaiswal121.demo.Model.CartItem;
import com.piyushjaiswal121.demo.R;

import java.util.List;

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


    private Context context;
    private List<CartItem> cartItems;
  

    public CartRecycler(Context context, List<CartItem> cartItems) {
        this.context = context;
        this.cartItems = cartItems;
        
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       View v = LayoutInflater.from(context).inflate(R.layout.cart_recycler_view,parent,false);
       return new  MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position)
 {
             holder.id.setText(cartItems.get(position).getName());
             holder.quantity.setText("Quantity "+String.valueOf(cartItems.get(position).getQuantity()));
             holder.price.setText("Price "+String.valueOf(cartItems.get(position).getPrice()));
            }

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

    static class MyViewHolder extends RecyclerView.ViewHolder
    {


      TextView id;
      TextView quantity;
      TextView price;
      ImageView imageView;

        MyViewHolder(@NonNull View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.textView);
            quantity = itemView.findViewById(R.id.quantity);
            price = itemView.findViewById(R.id.price);
            imageView = itemView.findViewById(R.id.closeImage);
        }
    }
}

You need to create a static class to connect layout file with adapter and extends recycler.adapter to make it adapter and after extending you need to override all three methods as written above in the code section.

Merge Adapter

Now, everything is complete. You only need to merge the adapter to recycler view

package com.piyushjaiswal121.demo.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class CartActivity extends AppCompatActivity {
    
    private CartRecycler recyclerAdapter;
    private List<CartItem> cartItemList = new ArrayList<>();
    private Context context;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_actvity);
        context = getApplicationContext();
      
        recyclerAdapter = new CartRecycler(context, cartItemList);
        RecyclerView recyclerView = findViewById(R.id.recycler_cart_view);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
 recyclerView.setLayoutManager(layoutManager);
    }

@Override
protected void onStart()
{
super.onStart();
cartItemList.add("ABC",10,1,0);

cartItemList.add("ABCD",101,1,1);

cartItemList.add("ABCE",10,1,2);

cartItemList.add("ABCF",10,1,3);

cartItemList.add("ABCG",10,1,4);
        recyclerView.setAdapter(recyclerAdapter);
}

   

   

CartItemActivity is model class



public class CartItem {

    private String name;
    private Integer price;
    private Integer quantity;
    private Integer itemId;

    public CartItem(String name, Integer price, Integer quantity, int itemId) {
        this.name = name;
        this.price = price;
        this.itemId = itemId;
        this.quantity = quantity;
    }

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public String getName() {
        return name;
    }

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

    public Integer getPrice() {
        return price;
    }



    public void setPrice(Integer price) {
        this.price = price;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
}

Result

Now, if you run your app you will see your app something like this.

Note-> Data may be different from my data in recycler view

Reference Official Docs

recycler view in android
Recycler View
Sudhanshu is Technology geek and also a pro pubg player. I like to create content in my free time that helps others. Currently pursuing BCA from Noida and operating Geekstocode

Leave a Comment

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