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
sample code for text watcher
your_edittext.addTextChangedListener(new InputValidator());
private class InputValidator implements TextWatcher {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
}
}
your_edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do something
}
});
You need to use TextWatcher for this purpose. Here is an example on how to work with TextWatcher and Android textwatcher API.
Another alternative is:
your_edittext.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
First, create an OnEditorActionListener
(as a private instance variable, for example):
private TextView.OnEditorActionListener mEnterListener =
new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
/* If the action is a key-up event on the return key, do something */
}
return true;
});
Then, set the listener (i.e. in your onCreate
method):
EditText mEditText = (EditText) findViewById(...);
mEditText.setOnEditorActionListener(mEnterListener);