I have a EditText
. I wamt tp do something, when the user presses the Enter key while changing EditText
. How can I do that?
The most simplest method:
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
First, create an
OnEditorActionListener
(as a private instance variable, for example):Then, set the listener (i.e. in your
onCreate
method):sample code for text watcher
Another alternative is:
You need to use TextWatcher for this purpose. Here is an example on how to work with TextWatcher and Android textwatcher API.