Home Blog Page 70

Android RecyclerView with EditText Example + Expense sum calculation

2
RecyclerView with EditText Example
RecyclerView with EditText Example

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will build a app that has a recyclerview with a list of view items and each list item in adapter has a Expense name (TextView) and a EditText field where user can enter the expense he spent for that expense.
Check out below screenshot

android recyclerview with expenses

Android Recyclerview with edittext example

OUTPUT

Have a look at my android project structure for easy understanding of the android tutorial on Recyclerview with editText Field.

Android Project Structure

So as you can see in above project structure, i have created 2 folder one for Recyclerview Adapter and a Data model that hold our dataSet that will be displayed in androidx Recyclerview.

Java Class

  • Adapter.java: That will help to inflate view in recyclerview.
  • ItemDatamodel.java: That holded list of data’s.

XML Layout

  • activity_main.xml : Where list of data will be displayed.
  • card_prod_list.xml : Eiew that will be shown to display particular list of items.

Recyclerview android example with edittext (source code)

UI XML Source Code below

card_prod_list.xml

Cardview that get generated when list of passed from activity to recyclerview adapter
<?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"
    android:tag="cards main container">

    <androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        card_view:cardBackgroundColor="#ffffff"
        card_view:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2">

            <TextView
                android:id="@+id/textViewExpName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center"
                android:layout_weight="1"
                android:paddingLeft="5dp"
                android:text="Product"
                android:textStyle="italic|bold"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000000"
                android:textSize="16sp" />

            <EditText
                android:id="@+id/ExpHeld"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:backgroundTint="#000000"
                android:gravity="center"
                android:hint="Value"
                android:inputType="number"
                android:textColor="#000000"
                android:textColorHint="#989898"
                android:textSize="14sp" />


            <Button
                android:id="@+id/ExpBimageSelect"
                android:layout_width="0dp"
                android:visibility="gone"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Select Image"
                android:textSize="6dp" />
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

activity_main.xml

This XML design simple has a recyclerview widget where all the generated list of data will get displayed.

recycler view acitivity main
<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

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



    <LinearLayout
        android:background="#A7B4FF"
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Total Expenses ₹ 0.00 "
                android:textSize="20sp"
                android:textStyle="italic"
                android:id="@+id/totalExpense"
                android:layout_gravity="center"/>

            <Button
                android:id="@+id/submitexpenses"
                android:paddingLeft="60dp"
                android:paddingRight="60dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Save"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

that all in xml layout you need to add. now let’s jump to java source : android recyclerview adapter and datamodel.

Java source : android recyclerview adapter and datamodel.

ItemDatamodel.java

Our DataModel class holder 2 kinds of datatype i.e integer and a string.
interger to hold Expense Id and String that holds ExpenseName.

package com.example.recyclerview_image_pick.datamodel;

public class ItemDatamodel {

    int ExpenseId;
    String ExpenseName;

    public ItemDatamodel(int expenseId, String expenseName) {
        ExpenseId = expenseId;
        ExpenseName = expenseName;
    }

    public int getExpenseId() {
        return ExpenseId;
    }

    public String getExpenseName() {
        return ExpenseName;
    }
}

Adapter.java

Check out the comment in code to under the Android Recyclerview Adapter code.

package com.example.recyclerview_image_pick.Adapter;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.example.recyclerview_image_pick.R;
import com.example.recyclerview_image_pick.datamodel.ItemDatamodel;

import java.util.ArrayList;

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


    View rootView;

    Context context;

    private ArrayList<ItemDatamodel> dataSet;

    // Usered Entered Expense amt will be stored in ExpAmtArray
    ArrayList<String> ExpAmtArray = new ArrayList<String>();

    boolean isOnTextChanged = false;
    int ExpenseFinalTotal = 0;
    TextView textviewTotalExpense;

    //constructor with dataSet passed from MainActivity when Adapter is called
    public Adapter(ArrayList<ItemDatamodel> dataSet) {
        this.dataSet = dataSet;
    }

    //Recyclerview ViewHolder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView expensesName;
        EditText expHeld;
        Button imageButton;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            // finding view by view id.
            expensesName = (TextView) itemView.findViewById(R.id.textViewExpName);
            expHeld = (EditText) itemView.findViewById(R.id.ExpHeld);
            imageButton = (Button) itemView.findViewById(R.id.ExpBimageSelect);
        }
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        // Initialize view for recyclerview
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_prod_list, parent, false);

        context = parent.getContext();
        rootView = ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content);

        textviewTotalExpense = (TextView) rootView.findViewById(R.id.totalExpense);
        //attach view to MyViewHolder
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

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

        //initialize the view with view holder
        TextView expensesName = holder.expensesName;
        EditText expHeld = holder.expHeld;
        Button imageButton = holder.imageButton;

        expensesName.setText(dataSet.get(position).getExpenseName());

        // EditText with TextWatcher Listens each time when user enter value in edittext in recyclerview
        expHeld.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //using this boolean because sometime when user enter value in edittxt
                //afterTextchanged runs twice to prevent this, i m making use of this variable.
                isOnTextChanged = true;
            }

            @Override
            public void afterTextChanged(Editable editable) {
                //so this will trigger each time user enter value in editText box
                ExpenseFinalTotal = 0;
                if (isOnTextChanged) {
                    isOnTextChanged = false;

                    try {
                        ExpenseFinalTotal = 0;


                        for (int i = 0; i <= position; i++) {

                            int inposition1 = position;
                            if (i != position) {
                                //store 0  where user select position in not equal/
                                ExpAmtArray.add("0");

                            }else {

                                // store user entered value to Array list (ExpAmtArray) at particular position
                                ExpAmtArray.add("0");
                                ExpAmtArray.set(inposition1,editable.toString());

                                break;
                            }

                        }

                        // for statement to loop to the array, to calculate the Expense total.
                        for (int i = 0; i <= ExpAmtArray.size() - 1; i++) {

                            int tempTotalExpenase = Integer.parseInt(ExpAmtArray.get(i));
                            ExpenseFinalTotal  = ExpenseFinalTotal + tempTotalExpenase;

                        }

                      textviewTotalExpense.setText("Total Expenses: ₹ "+String.valueOf(ExpenseFinalTotal));
                    }catch (NumberFormatException e)
                    {
                        // catch is used because, when used enter value in editText and remove the value it
                        // it will trigger NumberFormatException, so to prevent it and remove data value from array ExpAmtArray
                        //then
                        // re-perform loop total expense calculation and display the total.

                        ExpenseFinalTotal = 0;
                        for (int i = 0; i <= position; i++) {
                            Log.d("TimesRemoved", " : " + i);
                            int newposition = position;
                            if (i == newposition) {
                                ExpAmtArray.set(newposition,"0");

                            }

                        }
                        for (int i = 0; i <= ExpAmtArray.size() - 1; i++) {

                            int tempTotalExpenase = Integer.parseInt(ExpAmtArray.get(i));
                            ExpenseFinalTotal  = ExpenseFinalTotal + tempTotalExpenase;

                        }
                       textviewTotalExpense.setText("Total Expenses: ₹ "+String.valueOf(ExpenseFinalTotal));
                    }

                }
            }
        });
    }

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }


}

MainActivity.java

package com.example.recyclerview_image_pick;

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

import android.os.Bundle;
import android.util.Log;

import com.example.recyclerview_image_pick.Adapter.Adapter;
import com.example.recyclerview_image_pick.datamodel.ItemDatamodel;

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

public class MainActivity extends AppCompatActivity {

    private static ArrayList<ItemDatamodel> data;
    ItemDatamodel itemDatamodel;
    // list of Expensesname
    String[] Expensesname = {"Rent","Coffee","Lunch","Dinner","Transport","Other"};

    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view_expenses);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        
        data = new ArrayList<>();
        
        // generate ArrayList and store in data model
        for(int i =0;i<Expensesname.length;i++){
            itemDatamodel = new ItemDatamodel(
                    i,
                    Expensesname[i]
            );
            data.add(itemDatamodel);
        }

       // call Adapter class by passing ArrayList data
        adapter = new Adapter(data);
        // set adapter to recyclerview
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}

#video Tutorial will be uploaded soon on my youtube channel.

Similar Tutorial

How to add search filter to recyclerview adapter.

Firebase UI RecyclerView Adapter

How to show grid view in recyclerview android

5 Mistakes Flutter Beginner make or any software developer does

0
5 Mistakes Flutter Beginner make

Hi Guys, Welcome to Proto Coders Point.

Here are some key point that you need to take care off while your are into learning of flutter development or any other programming language.

This Blog post is special for beginner in flutter developer but same point also applies for others.

TOP 5 MISTAKES WILE LEARNING DEVELOPMENT

  1. Being too much a tutorial watching Guy.
  2. Start directly with cross platform development.
  3. Not staying consistent in learning flutter or any other.
  4. Directly Jumping/Implementing trending flutter library.
  5. Not Implementing knowledge in real projects.

1. Being too much a tutorial watching Guy

Don’t be rely to much on tutorials, if you are beginner consider learning flutter or any other development from multiple sources so that you get idea and find your own ways to solve your software development problem.

2. Start directly with cross platform development

Do not jump directly into learning cross platform development with flutter or React Native or any other cross development, always start with learning native like (Android – Java / kotlin or IOS – swift) is a key to learn how individual platform is built.
If you start directly with cross playform then there are more chances that you may get stuck because of individual platform requirement.

3. Not staying consistent in learning flutter or any other.

Upgrading ourselves by being consistent in learning flutter or any other programming stuff.

Being upgraded with latest technology is very important in an IT field.

Being consistent in any field is the way to success.

Many beginner in flutter jump directly into library that are in trending such as statemanagement using GetX, Bloc ,Provider.

If you do this then you many miss many basic feature of flutter dart, so just complete the basic of flutter first, understand how flutter setState works then use those libraries, some library are necessary other feature can be achieved by DIY Solution.

5. Not Implementing knowledge in real projects.

I saw people, they just complete a course in a particular field (flutter course) an start searching for a job as soon as they complete the futter course or any other. some people may get job immediatly but maximum people will fail to clear job interview due to lack of experience. (Check out Flutter Interview Question and answer asked in interview round)
Instead, As soon as you complete the course start making flutter apps or any other android, IOS, Web for your practice or just try to get a freelance projects work for them get knowlegde & experience then apply for a good job.

Check out Pros of flutter in 2021

Solution for Flutter app not working on some devices

0
Solution for flutter app not running on some devices

Hi Guys, Welcome to Proto Coders Point, I got query from one of my subscriber on youtube channel saying his flutter application is not working on some of devices.

Then i tried to solve his problem manually by myself then after some research on stackoverflow, github and all, i got to the solution.

Solution for flutter app not running on some devices

Here are some solution i have tried on my flutter app and that worked for me. (HOPE IT WORKS FOR YOU TO)

  1. Run the app on a Physical Device :
    If you are using a Emulator to test your flutter application then, just check in your physical device.
  2. Sign in config Debug / Release :
    With my experience i observed that beginner in flutter forgot to change sign in config from debug to release, if app is generated in debug mode, that particular app will not work on mobile devices where developers mode is disable.
    CHECK OUT THIS VIDEO BELOW TO GENERATE SIGNED APK

Proper way to generate signed apk from flutter application project

Suggested Atricles

How to get Flutter device info

How to change package name in flutter

0
how to change package name in flutter
how to change package name in flutter

This package library will make it very easy and fast to change flutter android package name.

How to use flutter change package name

So, Let’s begin with how to alter android package name in your flutter application.

1. Adding dev dependencies

Open <flutter project> / pubspec.yaml under this file look for dev_dependencies : section, just below it add change app package name, as shown in below screenshot.

dev_dependencies:
  change_app_package_name: ^0.1.2  
alter package name

2. Updating Flutter pub get

Once you have added any new dependencies in pubspec.yaml file, you always need to update it,

Then, to do that you need to run a commant i.e.

flutter pub get

Then, this commend will download the latest dependencies library files in your flutter project External Libraries, in our case it change_app_package_name.

3. Running a command to alter package name

You just need to run a command that will alter package name of your flutter android module.

See down of your IDE(Android Studio/VsCode) you may see terminal open it and just paste below cmd that will automatically change package name of your project.

flutter pub run change_app_package_name:main com.new.package.name

What this library does:

  • Update AndroidManifest.xml file release,debug & profile.
  • Update build.gradle file.
  • Update Activity’s file in your android module, Both java & Kotlin is supported.
  • Moves MainActivity file to new package directory.
  • Delete old package directory.

Video Tutorial

Recommended post

How to change Flutter App Launcher Icon.

How to install Flutter Plugin in android Studio.

How to Generate Signed apk in flutter android studio

0
How to Generate Signed apk in flutter android studio

Hi Guys,

Welcome to Proto Coders Point, In this article we will learn how to generate signed apk of your flutter code in android studio. There are various ways to create a APK file, But in this article we will check out the simplest & easiest way to do it.

NOTE: THIS ARTICLE WILL BE JUST ON GENERATING SIGNED APK FOR ANDROID PUBLICATION.

How to Build Signed APK?

You have completed your flutter project & is ready to be published to the world through play store.

Then, now you are here to know how to generate signed apk of your flutter project.

Let’s Begin, Here is my Flutter Project built in android Studio(IDE),

Flutter Project Structure – Generate Signed APK.

So let’s see the process of building a signed APK in flutter project.

VIDEO TUTORIAL

Time needed: 5 minutes

How to generate signed apk in flutter android studio

  1. Open Android module in android studio

    In Android Studio tab bar, Navigate towords Tools > Flutter > then Open Android module in android Studio.

    Check out the screenshot for path reference.
    open android module in android studo - flutter

  2. Open Project in new window

    This will open android module version of your flutter project
    Open as new window - android studio

  3. Generate Signed Bundle/APK file

    Now, you will have a new window of your android studio, where your flutter project android verison is been opened.

    Click on Build > Generate Signed Bundle/APK


    build generate signed bundle apk
    After Clicking on it you will see a new pop dialog box, there select apk/bundle.

  4. Creating new key store path

    Click on create new
    creating new keystore
    Here set a key store path there you want to create key store for your flutter project.

  5. Configure signing in gradle

    Open /android/app/build.gradle file
    Just before android block: add below keystoreProperties

    def keystoreProperties = new Properties()
    def keystorePropertiesFile = rootProject.file(‘key.properties’)
    if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
    }
    android {

    }


    then add below code before buildType block:

    signingConfigs {
    release {
    keyAlias keystoreProperties['keyAlias']
    keyPassword keystoreProperties['keyPassword']
    storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
    storePassword keystoreProperties['storePassword'] }
    }
    buildTypes {
    release {
    signingConfig signingConfigs.release
    }
    }

  6. flutter clear

    Please note that after making any changes in build.gradle file, you need to run as comment in your IDE “flutter clear” so the the changes will affect in signing process.

  7. Select Build Varient as release

    After creating keystore & seting Alias & password hit next button.

    final step release app
    If you are creating apk for final app release on play store then select release else if you are giving for testing you can select as bebug.

  8. Full APK Signature

    You can see in above 5th step i have selected V2 (Full APK signature) to create full release version of my android flutter project

  9. Locate to the path

    Now we have created signed apk successfully, To locate to the path where release version of apk is created check out below screenshot.
    locate the path where apk is created

This article is been Refered from StackoverFlow : How to build signed apk from Android Studio for Flutter.

Easy way to set Flutter app icon

How to add Search Filter to Recyclerview – Android Recyclerview Filterable

1

Hi Guys, Welcome to Proto Coders Point, In this android tutorial article we will learn how to add a Search filter to a RecycleView in Toolbar SearchView in Real-time.

Video Tutorial on filter recyclerview android using SearchView

Android Recyclerview Adapter Filterable – Android search filter

Required Dependencies

implementation 'androidx.recyclerview:recyclerview:1.1.0'  //recycleview

implementation 'androidx.cardview:cardview:1.0.0'

Add both of the above dependencies in your app.level build.gradle file under dependencies.


To achieve this feature, First, you need to create a menu item in your android project.

Steps to create a menu item in android

In your android project > res > create a new package(folder) name it as “menu”,

Then, in the menu package create an XML file “search_menu.xml”

how to create a menu item in android

search_menu.xml

Then, Add the following code to the menu.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:title="Search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
</menu>

Here, In the above code, the menu is given an id, an Icon (a search icon, you need to create a vector search image in your drawable folder),
And to make it expandable I am using shows action with collapseActionView attribute, By doing this we can the menu as an icon in our android app bar when this icon is been pressed/clicked it will expand, and hence the user can input text in Android SearchView.


Add some images

You need to add some images under the drawable folder so that you can show images in your recycler view cards.

Eg: In my case, I have just created few vector images in my drawable, you can see in the below screenshot

android vector images

Now, let’s procedure in creating a Recyclerview with Filterable search filter – android filter recycler view using search view in toolbar


Custom layout for RecyclerView

custom_layout_for_recyclerview.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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:id="@+id/game_id"
        app:cardBackgroundColor="#E8E0E0"
        app:cardCornerRadius="15dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageview"
            android:layout_width="80dp"
            android:layout_height="80dp"
            />

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textSize="30sp"
            android:textColor="@color/black"
            android:layout_marginLeft="25dp"
            android:layout_gravity="center"/>
    </LinearLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>

In this custom layout for recycler view, we have 2 views i.e. ImageView & a TextView, Where we will display our Data Model Data in a form of recyclerview.


Data Model that hold List of Data’s

ItemDataModel.java

package com.example.recycleviewexample.DataModel;

public class ItemDataModel {

    int image;
    String txtname;

    public ItemDataModel(int image, String txtname) {
        this.image = image;
        this.txtname = txtname;
    }

    public int getImage() {
        return image;
    }

    public String getTxtname() {
        return txtname;
    }
}



Recyclerview Adapter

Then, we need a RecyclerView Adapter that will help us in creating views and show a list of data in recycleview.

Here, In the below lines of codes, We Implement a Filterable interface into our RecyclerView Adapter class and then create our own Filter Method, Where we are applying filtering logic using perform filtering method which will filter return result to publishresult method and then apply the searched Filter data and show it to the user on the RecyclerViewscreen.

There I am using 2 array list,
First One holds a complete ArrayList of data’s and
the second holds the only ArrayList of Data that a user search in the SearchView Search Filter.

RecyclerAdapter.java

package com.example.recycleviewexample.Adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.example.recycleviewexample.DataModel.ItemDataModel;
import com.example.recycleviewexample.R;

import java.util.ArrayList;

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder>  implements Filterable {

    private ArrayList<ItemDataModel> dataSet;
    private ArrayList<ItemDataModel> FullList;
    
    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView tvName;

        MyViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageview);
            tvName = itemView.findViewById(R.id.tvName);

        }
    }

    public RecycleAdapter(ArrayList<ItemDataModel> itemList) {
        this.dataSet = itemList;
        FullList = new ArrayList<>(itemList);
    }

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

    @Override
    public void onBindViewHolder(@NonNull RecycleAdapter.MyViewHolder holder, int position) {
        ItemDataModel currentItem = dataSet.get(position);
        holder.imageView.setImageResource(currentItem.getImage());
        holder.tvName.setText(currentItem.getTxtname());

    }

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

    @Override
    public Filter getFilter() {
        return Searched_Filter;
    }

    private Filter Searched_Filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            ArrayList<ItemDataModel> filteredList = new ArrayList<>();
            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(FullList);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();
                for (ItemDataModel item : FullList) {
                    if (item.getTxtname().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataSet.clear();
           dataSet.addAll((ArrayList) results.values);
            notifyDataSetChanged();
        }
    };
}

MainActivity.java

Then, In our MainActivity, we are creating a List of Data and passing the data to RecyclerView Adaptor to display them,

To show a Search View Menu in our App Toolbar we are using @Override onCreateOptionsMenu where we will use MenuInflater to show Search Menu,
Then connect our SearchView with our Menu Search,

using setOnQueryTextListener we are detecting onQueryTextChange where user enter Search Filter String we will pass to the string to our adapter method (adapter.getFilter().filter(newText)) 

Then our adapter method will create new dataSet and display the searched data to the user.

MainActivity.java

package com.example.recycleviewexample;

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

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.SearchView;

import com.example.recycleviewexample.Adapter.RecycleAdapter;
import com.example.recycleviewexample.DataModel.ItemDataModel;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecycleAdapter adapter;
    private ArrayList<ItemDataModel> dataSet;

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

        fillExampleList();
        setUpRecyclerView();
    }

    private void fillExampleList() {
        dataSet = new ArrayList<>();
        dataSet.add(new ItemDataModel(R.drawable.computer, "Computer 1"));
        dataSet.add(new ItemDataModel(R.drawable._self_improvement, "Meditation 1"));
        dataSet.add(new ItemDataModel(R.drawable.rowing, "Rowing 1"));
        dataSet.add(new ItemDataModel(R.drawable.running, "Running 2"));
        dataSet.add(new ItemDataModel(R.drawable.rowing, "Rowing 2"));
        dataSet.add(new ItemDataModel(R.drawable.computer, "Computer 2"));
        dataSet.add(new ItemDataModel(R.drawable.running, "Running 2"));
        dataSet.add(new ItemDataModel(R.drawable._self_improvement, "Meditation 2"));
        dataSet.add(new ItemDataModel(R.drawable.running, "Running 3"));
    }
    private void setUpRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycle_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        adapter = new RecycleAdapter(dataSet);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search_menu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                Log.d("newText1",query);
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d("newText",newText);

                adapter.getFilter().filter(newText);
                return false;
            }
        });
        return true;
    }
}

activity_main.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:background="#e0dfdf"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycle_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="81"
        android:scrollbars="vertical" />

</LinearLayout>


Recommended Android articles

Send user-entered recyclerview edit text Array list data to database (PHPMyAdmin)

Recyclerview with card view android example – Android X Tutorial

RecyclerView With GridLayoutManager Show Grid View in androidx

Firebase UI RecyclerView Adapter Android Tutorial with Example