Android RecyclerView with EditText Example

android listview edittext, android recyclerview with edittext, Kotlin Generate VCF, android select multiple images from gallery

Android RecyclerView with EditText example tutorial guide you to add edittext in the every cell or child of the recyclerview.

I have used a Model class to maintain proper data and the value of edittext in the recyclerview.

You will also learn how to fetch value of the EditText of all the rows. We will pass these values to the Next Activity.

Most common problems regarding this topic are

  1. Value of edittext get change when scrolling
  2. Edittext loses content on scroll in recyclerview

  3. Edittext loses focus in recyclerview

This tutorial will solve all the above problems in this Android RecyclerView with EditText Example.

We will use the TextWatcher class to control the changes of the edittext.

Check out the output of Android RecyclerView With Edittext tutorial.

Also Read,

1. Make RecyclerView item

Create a resource file and give it a name rv_item.xml

This file shows how a single cell of recyclerview will be look like.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:background="@color/colorAccent"
    tools:context=".MainActivity">

    <android.support.v7.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="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="0dp"
        card_view:cardCornerRadius="4dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:textColor="#000"
                android:text="TextView:"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:id="@+id/editid"
                android:layout_marginTop="10dp"
                android:paddingLeft="10dp"
                android:textColor="#000"
                android:text="hello"
                />

        </LinearLayout>


    </android.support.v7.widget.CardView>
</RelativeLayout>

2. Updating build.gradle(Module:app)

Add below lines in build.gradle(Module:app)

 compile 'com.android.support:recyclerview-v7:26.1.0'
 compile 'com.android.support:cardview-v7:26.1.0'

Above lines will add support for recyclerview and cardview. By default, it is not supported in android studio project.

Full code

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.parsaniahardik.recyclerview_edittext"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
}

3. Preparing Model Class

Make a new java class named EditModel.java

package com.example.parsaniahardik.recyclerview_edittext;

/**
 * Created by Parsania Hardik on 17-Apr-18.
 */

/**
 * Created by Parsania Hardik on 03-Jan-17.
 */
public class EditModel {

    private String editTextValue;

    public String getEditTextValue() {
        return editTextValue;
    }

    public void setEditTextValue(String editTextValue) {
        this.editTextValue = editTextValue;
    }
}
  • In our recyclerview, only the value of edittext is changing so we need to maintain it with model class.
  • Above class is that model who holds the getter and setter methods for the value edittext.

4. Adapter class

Create a new class and it’s name should be CustomAdapter.java

import android.content.Context;
import android.support.v7.widget.RecyclerView;
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.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

/**
 * Created by Parsania Hardik on 17-Apr-18.
 */

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

    private LayoutInflater inflater;
    public static ArrayList<EditModel> editModelArrayList;


    public CustomAdapter(Context ctx, ArrayList<EditModel> editModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.editModelArrayList = editModelArrayList;
    }

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

        View view = inflater.inflate(R.layout.rv_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) {


        holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
        Log.d("print","yes");

    }

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

    class MyViewHolder extends RecyclerView.ViewHolder{

        protected EditText editText;

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

            editText = (EditText) itemView.findViewById(R.id.editid);

            editText.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) {

                      editModelArrayList.get(getAdapterPosition()).setEditTextValue(editText.getText().toString());
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });

        }

    }
}

First of all, consider the below code

private LayoutInflater inflater;
public static ArrayList<EditModel> editModelArrayList;


    public CustomAdapter(Context ctx, ArrayList<EditModel> editModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.editModelArrayList = editModelArrayList;
 }
    • First line will create the object of the LayoutInflater class.
    • Second will create one Arraylist with objects of the EditModel class.
    • Then I have created a constructor of the adapter class.
    • Compiler will get a context and arraylist from the parameter of this constructor.

Now look at the below code

 @Override
    public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) {


        holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
        Log.d("print","yes");

 }
  • In the above code, we are setting the value of the EditText.
  • Here, we are using that Arraylist with the objects of the EditModel class.
  • Main logic is present in adapter class. We will change and store the value of edittexts in this.
    Look at the following code
editText.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) {

                      editModelArrayList.get(getAdapterPosition()).setEditTextValue(editText.getText().toString());
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });
  • When user changes the value of edittext, above lines will be excuted.
  • When text is being changed, we will store the new value of edittext in arraylist.
  • Arraylist is made public in the adapter class. This arraylist can be used anywhere in the whole application.

5. Making next activity

Make a new activity with name NextActivity.java

Add below source code in this class

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class NextActivity extends AppCompatActivity {

    private TextView tv;

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

        tv = (TextView) findViewById(R.id.tv);

        for (int i = 0; i < CustomAdapter.editModelArrayList.size(); i++){

            tv.setText(tv.getText() + " " + CustomAdapter.editModelArrayList.get(i).getEditTextValue() +System.getProperty("line.separator"));

        }


    }
}
  • In this next activity, we will show all the values of edittexts.
  • Here, we have used that public arraylist to fetch the values.

Updating activity_next.xml

Copy below code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:id="@+id/tv"/>

</RelativeLayout>

6. Changing MainActivity.java

Update MainActivity.java class with following source code

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private RecyclerView recyclerView;
    private CustomAdapter customAdapter;
    public ArrayList<EditModel> editModelArrayList;

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        btn = (Button) findViewById(R.id.btn);

        editModelArrayList = populateList();
        customAdapter = new CustomAdapter(this,editModelArrayList);
        recyclerView.setAdapter(customAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

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

    }

    private ArrayList<EditModel> populateList(){

        ArrayList<EditModel> list = new ArrayList<>();

        for(int i = 0; i < 8; i++){
            EditModel editModel = new EditModel();
            editModel.setEditTextValue(String.valueOf(i));
            list.add(editModel);
        }

        return list;
    }

}

Pay attention at the below code

 editModelArrayList = populateList();
  • Above line is creating a data structure. Compiler will use populateList() method for this purpose.

Following is the code for populateList() method.

 private ArrayList<EditModel> populateList(){

        ArrayList<EditModel> list = new ArrayList<>();

        for(int i = 0; i < 8; i++){
            EditModel editModel = new EditModel();
            editModel.setEditTextValue(String.valueOf(i));
            list.add(editModel);
        }

        return list;
}
  • In this method, compiler will run one for loop for seven times.
  • In the each iteration, it will create one object of the EditModel class. Then it will set the value of the edittext.

Read the following code

  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,NextActivity.class);
                startActivity(intent);
            }
        });
  • Compiler will run the above code when the user clicks on the button.
  • It will open a Next Activity via above code snippet.

Add below code in 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Pass All EditText value to Next Activity"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="15dp"/>


</LinearLayout>

I have taken one button and one recyclerview in the main layout.

Thus, edittext is not losing focus neither it’s value is changed on scroll.

We always try to solve the hard and complex real world problems regarding android development.

Keep visiting other tutorials for other wonderful logic and time saving techniques.

So, it was all for the tutorial.

If you have any questions regarding logic of adapter class or anything else, then feel free to ask in comment section.

Course Recommendation

If you want to enhance your knowledge in android development then we recommend the below course.

Android development course for learners.

Download Source Code For Android RecyclerView With EditText Tutorial

[sociallocker]Recyclerview_Edittext [/sociallocker]