Wednesday, August 19, 2015

How to use EditText TextChangedListener in Android

MainActivity.java

package com.cfsuman.androidtutorials;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                // Get the widgets reference from XML layout
                EditText et = (EditText) findViewById(R.id.et);
                TextView tv = (TextView) findViewById(R.id.tv);


                // Set the edit text text changed listener
                et.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(
                                CharSequence s, int start,
                                int count, int after) {
                                // Do some thing now
                        }

                        @Override
                        public void onTextChanged(
                                CharSequence s, int start,
                                int before, int count) {
                                // Change the TextView background color
                                tv.setBackgroundColor(Color.YELLOW);

                                // Get the EditText text and
                                // display it on TextView
                                tv.setText(et.getText());
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                                // Do something at this time
                        }
                });
        }
}
activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#eae8e3"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:padding="15dp"
        android:layout_margin="15dp"
        android:textSize="20sp"
        />
    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:hint="This is initial text"
        android:layout_below="@id/tv"
        />
</RelativeLayout>