Home Android Android RecyclerView with EditText Example + Expense sum calculation

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 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

2 Comments