The Blog

onChange event on EditText in Android

09 Ott 10

Sooner or later you’ll have to deal with it. If you’re an html developer and you write also in javascript you’ll surely know the onchange event.

Unfortunately it’s a little bit tricky to find the same event on android.

The onChange event is helpful when you’ve to deal with the following things:

  • Let the user know (in realtime) how many characters he typed.
  • Let the user know (in realtime) how many remaining characters he is allowed to type.
  • Make realtime processing of the content ( like sending it online and fetch some partial results of the partial typed edittext )

You’ve to implement your own instance of TextWatcher and let the edittext know that you want to be notified at each change by calling the method EditText.addTextChangedListener.

Below i will give you a simple example ( it’s written on the fly but you’ll understand the idea )

[sourcecode lang=”java”]
((EditText)findViewById(R.id.et_testo)).addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {
((TextView)findViewById(R.id.numcaratteri)).setText(String.format(getString(R.string.caratteri), s.length()));

}

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

}

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

}

});

[/sourcecode]

Comments