Android EditText text change listener example

In this example we will learn the following
  • Create an EditText using XML layout resource 
  • Attach a Text change listener to the EditText
  • Display the text inside a TextView upon change

android edittext text change listener example
android edittext text change listener example

Source for the Screen Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:paddingBottom="20dp"
  android:text="@string/input_text" 
  android:textAppearance="?android:attr/textAppearanceMedium" />

 <EditText android:id="@+id/myTextBox" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:ems="10" 
  android:gravity="top|left"
  android:inputType="textMultiLine" android:lines="5" android:minLines="2"
  android:paddingBottom="20dp" android:singleLine="false"
  android:scrollbars="vertical">

  <requestFocus />
 </EditText>
 <TextView android:id="@+id/textView2" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="@string/result_text"
  android:paddingBottom="10dp" 
  android:textAppearance="?android:attr/textAppearanceMedium" />

 <TextView android:id="@+id/myOutputBox" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:padding="10dp"
  android:text="" 
  android:textAppearance="?android:attr/textAppearanceMedium" />


</LinearLayout>

Source for the Activity - AndroidEditTextChangeActivity.java

package com.as400samplecode;

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

public class AndroidEditTextChangeActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  EditText myTextBox = (EditText) findViewById(R.id.myTextBox);
  myTextBox.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {
   }

   public void beforeTextChanged(CharSequence s, int start, 
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start, 
     int before, int count) {
   TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);
   myOutputBox.setText(s);
   }
  });

 }
}

1 comment:

Unknown said...

thanks. This is very good.

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.