CoderzHeaven

February 16, 2012

Listening to EditText input in Android using TextWatcher.

Hello all…….

In todays post I will show you how to listen to an EditText input in Android.
Often we need this in our applications.
We implement this with the help of TextWatcher class.

Here is the java code for this.

package com.coderzheaven.test;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.widget.EditText;import android.widget.Toast;public class Test extends Activity{private EditText ed_txt;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);ed_txt=(EditText)findViewById(R.id.EditText01);ed_txt.addTextChangedListener(new TextWatcher() {public void afterTextChanged(Editable s) {if(ed_txt.getText().toString().trim().length() > 0){if(Integer.parseInt(ed_txt.getText().toString().trim()) < 20 || Integer.parseInt(ed_txt.getText().toString().trim()) > 120){ed_txt.setTextColor(Color.GREEN);}else{Toast.makeText(getApplicationContext(), "High", Toast.LENGTH_SHORT).show();ed_txt.setTextColor(Color.RED);}}}public void beforeTextChanged(CharSequence s, int start, int count, int after) {}public void onTextChanged(CharSequence s, int start, int before, int count) {}});}}

Here I am checking whether the input value in the edittext is between 20 and 120 if yes then change the text color to Green otherwise to Red.

Please leaveyour valuable comments on this post

Website PinFacebook TwitterMyspaceFriendfeedTechnoratidel.icio.usDiggGoogleStumbleUponPremium Responsive

Leave a Reply Cancel reply