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

  • 十窍通了九窍,多谢博主见解太精辟了.

  • Thanks, exactly what I’ve been looking for! 🙂

    Why is the Android documentation so lacking of good examples like this?

  • very nice information about android, thank for share 🙂

  • thanks Alot. Great work!

  • very nice information about android, thank for share 🙂

  • yoandi

    ciao andre ho visto il tuoi comenti in vari pagine de aggiornamento di htc dream.io sono estra disperato no riescco a farcela no so come mai.se tu vuoi farmi quel lavoro tramite teanviwer io ti pago tranquilamente.farmi sapere grazie. [email protected]

  • Pingback: Evento onChange en EditText en Android | Sentido Droid()