Android EditText TextWatcher

A

Android EditText TextWatcher Example

TextWatcher
This methods  will be called when the text is changed.
Text Watcher Having Three Events.

1.beforeTextChanged
2.onTextChanged
3.afterTextChanged
beforeTextChanged This means that the characters are about to be replaced with some new text. The text is  uneditable.   Use: when you need to take a look at the old text which is about to change.
onTextChanged Changes have been made, some characters have just been replaced. The text is uneditable.Use: when you need to see which characters in the text are new.
afterTextChanged The same as above, except now the text is editable.

main.xml:

<?xml version=“1.0” encoding=“utf-8”?>
<LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”>
<EditText
android:id=“@+id/url_field”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:layout_weight=“1.0”
android:maxLength=“100”
android:lines=“1” />
</LinearLayout>

MainActivity code:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends Activity implements TextWatcher {
EditText text;
int textCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText)findViewById(R.id.url_field);
text.addTextChangedListener(this);
}
/* TextWatcher Implementation Methods */
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int end) {
textCount = text.getText().length();
setTitle(“Message :: “+String.valueOf(textCount)+”/100″);
}
public void afterTextChanged(Editable s) {
}
}
screenshot:

About the author

prashant.koli
By prashant.koli

Category