Samantha Withanage Samantha Withanage - 1 year ago 125
Java Question

TextChangedListener - Differences between onTextChanged, beforeTextChanged and afterTextChanged

In my Android Project I have had to add a TextChangedListener to a edit text view. And there are three parts in it.

  • onTextChanged

  • beforeTextChanged

  • afterTextChanged

What are the differents of these three. I have had to implement a search of a table on the key lisner and for my case all these three looks the same. Also they functioned the same. When I input a part of a product name the table redraws with only those products contains that entered text in it. But I used the afterTextChanged part. My code is

EditProduct.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

// System.out.println("onTextChanged"+s);

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
// System.out.println("beforeTextChanged"+s);


public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// System.out.println("afterTextChanged"+s);

String new_prx = s.toString();

mini_productList = new ArrayList<Product>();

// mini_productList
int count = 0;
if (new_prx.equals("")) {


} else {

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

if (productList.get(i).getDescription().toString()
.substring(0, (new_prx.length()))
.equalsIgnoreCase(new_prx)) {






So can someone give me an explenation on these three. Thank you!!!!

Answer Source

onTextChanged runs during the text changing.

afterTextChanged runs immediately after the text is changed.

beforeTextChanged runs the instant before the text is changed.

Depending on when you want to assign variables or do things, you may want to run the code the instant before the change, or the instant after.

Here is an example of this:

String afterTextChanged = "";
String beforeTextChanged = "";
String onTextChanged = "";

protected void onCreate(Bundle savedInstanceState) {

    et = (EditText)findViewById(;

    et.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence s, int st, int b, int c) 
            onTextChanged = et.getText().toString();

        public void beforeTextChanged(CharSequence s, int st, int c, int a) 
            beforeTextChanged = et.getText().toString();

        public void afterTextChanged(Editable s) 
            afterTextChanged = et.getText().toString();
            Toast.makeText(Activity.this, "before: " + beforeTextChanged
                                           + '\n' + "on: " + onTextChanged 
                                           + '\n' + "after: " + afterTextChanged

In this case, let's say you changed the text from "h" to "hi", the output would be:

before: "h"
on: "hi"
after: "hi"