Reputation: 1505
I have an EditText
. I want that whenever user press enter key, automatically insert a number(incremental numbers). Should I use TextWatcher
interface or OnEditorActionListener
? If I use TextWatcher
, how to recognize enter
key.
I do this, but nothing happened.
View.OnKeyListener onEnter = new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
edtInput.addTextChangedListener(new HandlEventEditText(edtInput));
}
return false;
}
};
and HandlEventEditText
class
public class HandlEventEditText implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
editText.setText("4");
}
}
Upvotes: 2
Views: 71
Reputation: 10095
Solution:
Use like this:
editText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent keyevent) {
//If the keyevent is a key-down event on the "enter" button
if ((keyevent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
//...
// ...
// ...
return true;
}
return false;
}
});
You can enter the logic there, and your Enter key will do as you say.
Hope it helps.
Upvotes: 1