Android Knowledge

RecyclerView in Android Studio using Java – Easy 7 Steps Only!

recyclerview java android studio

Table of Contents

RecyclerView

RecyclerView is a part of the view group that contains a single view that is recycled repeatedly to display the corresponding data.

We have item_layout as our single view which will display our data repeatedly in a recycler format.

In ArrayList, we will define all our data such as images and text then with the help of Adapter and ViewHolder we will display the data.

Download Drawables

Click Here

Step-by-Step Implementation

Step 1: Open Android Studio and Create New Project.

Choose Empty Activity, Name the Project, and Click Finish.

Step 2: colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="lavender">#8692f7</color>

</resources>

themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.RecyclerKotlin" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/lavender</item>
        <item name="colorPrimaryVariant">@color/lavender</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>

strings.xml

<resources>
    <string name="app_name">Android Basic Tutorials</string>


    <string name="date">A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE
        value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.
        To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance
        must be normalized by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
        </string>

    <string name="rating">A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in stars.
        The user can touch/drag or use arrow keys to set the rating when using the default size RatingBar.
        The smaller RatingBar style ( R.attr.ratingBarStyleSmall) and the larger indicator-only style
        (R.attr.ratingBarStyleIndicator) do not support user interaction and should only be used as indicators.
        When using a RatingBar that supports user interaction, placing widgets to the left or right of the
        RatingBar is discouraged.</string>

    <string name="edit">A TextView displays text to the user and optionally allows them to edit it.
        A TextView is a complete text editor, however the basic class is configured to not allow editing.
        </string>

    <string name="camera">The Android framework includes support for various cameras and camera features
        available on devices, allowing you to capture pictures and videos in your applications.
        This document discusses a quick, simple approach to image and video capture and outlines an advanced
        approach for creating custom camera experiences for your users.</string>

    <string name="recyclerview">RecyclerView is the ViewGroup that contains the views corresponding to your data.
        Its a view itself so you add RecyclerView into your layout the way you would add any other UI element.
        Each individual element in the list is defined by a view holder object.
        RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView.
        It is an improvement on both of them and can be found in the latest v-7 support packages.
        It has been created to make possible construction of any lists with XML layouts as an item
        which can be customized vastly while improving on the efficiency of ListViews and GridViews.
    </string>
</resources>

Step 3: activity_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:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.appcompat.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="12dp"
        android:layout_marginStart="12dp"
        android:id="@+id/search"
        app:iconifiedByDefault="false"
        app:searchHintIcon="@null"
        app:queryHint="Search..."
        android:focusable="false"
        app:closeIcon="@drawable/ic_baseline_clear_24"
        app:searchIcon="@drawable/ic_baseline_search_24"
        android:background="@drawable/search_bkg"/>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"
        android:layout_marginTop="8dp"
        android:scrollbars="vertical"
        android:layout_below="@id/search"/>

</RelativeLayout>

recycler_item.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="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="250dp"
        android:id="@+id/recCard"
        app:cardElevation="8dp"
        app:cardCornerRadius="16dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="5.5">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:id="@+id/recImage"
                android:layout_weight="4"
                android:scaleType="centerCrop"
                android:src="@drawable/recycler_detail"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:weightSum="2"
                android:layout_weight="1.5"
                android:background="@drawable/card_border">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.3"
                    android:padding="10dp"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Title"
                        android:textSize="20sp"
                        android:maxLines="1"
                        android:textColor="@color/lavender"
                        android:id="@+id/recTitle"/>

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Desc"
                        android:textSize="18sp"
                        android:id="@+id/recDesc"
                        android:maxLines="0"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="0.7"
                    android:gravity="center">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Language"
                        android:textColor="@color/lavender"
                        android:textSize="18sp"
                        android:textAlignment="center"
                        android:id="@+id/recLang"/>

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

activity_detail.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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".DetailActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/detailTitle"
        android:layout_marginTop="14dp"
        android:text="Title"
        android:textSize="24sp"
        android:layout_gravity="center"
        android:textColor="@color/lavender"
        android:layout_marginBottom="12dp"/>

    <ImageView
        android:layout_width="400dp"
        android:layout_height="200dp"
        android:id="@+id/detailImage"
        android:padding="8dp"
        android:layout_gravity="center"
        android:src="@drawable/recycler_detail"
        android:scaleType="centerCrop"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Description"
        android:padding="20dp"
        android:layout_gravity="center"
        android:textColor="@color/lavender"
        android:textSize="18sp"
        android:id="@+id/detailDesc"/>

</LinearLayout>

Step 4: DataClass.java

package com.example.recyclerviewdetailed;

public class DataClass {

    private String dataTitle;
    private int dataDesc;
    private String dataLang;
    private int dataImage;

    public String getDataTitle() {
        return dataTitle;
    }

    public int getDataDesc() {
        return dataDesc;
    }

    public String getDataLang() {
        return dataLang;
    }

    public int getDataImage() {
        return dataImage;
    }

    public DataClass(String dataTitle, int dataDesc, String dataLang, int dataImage) {
        this.dataTitle = dataTitle;
        this.dataDesc = dataDesc;
        this.dataLang = dataLang;
        this.dataImage = dataImage;
    }
}

Step 5: MyAdapter.java

package com.example.recyclerviewdetailed;

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

import java.util.List;

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

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private Context context;
    private List<DataClass> dataList;

    public void setSearchList(List<DataClass> dataSearchList){
        this.dataList = dataSearchList;
        notifyDataSetChanged();
    }

    public MyAdapter(Context context, List<DataClass> dataList){
        this.context = context;
        this.dataList = dataList;
    }

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

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.recImage.setImageResource(dataList.get(position).getDataImage());
        holder.recTitle.setText(dataList.get(position).getDataTitle());
        holder.recDesc.setText(dataList.get(position).getDataDesc());
        holder.recLang.setText(dataList.get(position).getDataLang());

        holder.recCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, DetailActivity.class);
                intent.putExtra("Image", dataList.get(holder.getAdapterPosition()).getDataImage());
                intent.putExtra("Title", dataList.get(holder.getAdapterPosition()).getDataTitle());
                intent.putExtra("Desc", dataList.get(holder.getAdapterPosition()).getDataDesc());

                context.startActivity(intent);
            }
        });

    }

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

class MyViewHolder extends RecyclerView.ViewHolder{

    ImageView recImage;
    TextView recTitle, recDesc, recLang;
    CardView recCard;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);

        recImage = itemView.findViewById(R.id.recImage);
        recTitle = itemView.findViewById(R.id.recTitle);
        recDesc = itemView.findViewById(R.id.recDesc);
        recLang = itemView.findViewById(R.id.recLang);
        recCard = itemView.findViewById(R.id.recCard);
    }
}

Step 6: MainActivity.java

package com.example.recyclerviewdetailed;

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

import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    List<DataClass> dataList;
    MyAdapter adapter;
    DataClass androidData;
    SearchView searchView;

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

        recyclerView = findViewById(R.id.recyclerView);
        searchView = findViewById(R.id.search);

        searchView.clearFocus();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                searchList(newText);
                return true;
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 1);
        recyclerView.setLayoutManager(gridLayoutManager);
        dataList = new ArrayList<>();

        androidData = new DataClass("Camera", R.string.camera, "Java", R.drawable.camera_detail);
        dataList.add(androidData);

        androidData = new DataClass("RecyclerView", R.string.recyclerview, "Kotlin", R.drawable.recycler_detail);
        dataList.add(androidData);

        androidData = new DataClass("Date Picker", R.string.date, "Java", R.drawable.date_detail);
        dataList.add(androidData);

        androidData = new DataClass("EditText", R.string.edit, "Kotlin", R.drawable.edit_detail);
        dataList.add(androidData);

        androidData = new DataClass("Rating Bar", R.string.rating, "Java", R.drawable.rating_detail);
        dataList.add(androidData);

        adapter = new MyAdapter(MainActivity.this, dataList);
        recyclerView.setAdapter(adapter);
    }

    private void searchList(String text){
        List<DataClass> dataSearchList = new ArrayList<>();
        for (DataClass data : dataList){
            if (data.getDataTitle().toLowerCase().contains(text.toLowerCase())) {
                dataSearchList.add(data);
            }
        }
        if (dataSearchList.isEmpty()){
            Toast.makeText(this, "Not Found", Toast.LENGTH_SHORT).show();
        } else {
            adapter.setSearchList(dataSearchList);
        }
    }
}

Step 7: DetailActivity.java

package com.example.recyclerviewdetailed;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class DetailActivity extends AppCompatActivity {

    TextView detailDesc, detailTitle;
    ImageView detailImage;

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

        detailDesc = findViewById(R.id.detailDesc);
        detailTitle = findViewById(R.id.detailTitle);
        detailImage = findViewById(R.id.detailImage);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            detailDesc.setText(bundle.getInt("Desc"));
            detailImage.setImageResource(bundle.getInt("Image"));
            detailTitle.setText(bundle.getString("Title"));
        }
    }
}

Output

recyclerview java android studio

AK Bonus Points

If you have any queries or errors, please feel free to comment below 🙂

For detailed steps, watch our youtube video: RecyclerView in Android Studio using Java

Watch Retrieve Firebase Data in Profile YT Video: How to Retrieve Data from Firebase Database and Display in Profile Activity – Android Studio

Check our similar post here: Login and Signup using Firebase Authentication in Android Studio