I am working on Android. Previously i used onKeyListener
to handle specific action on key event.
However, this way seems not to solve my problem since almost all key would get disable once i have implemented that listener to my EditText
. After reading some topics in SO, i know that i should use TextWatcher instead, but i'm still wondering how to handle ENTER
key event inside because parameters provided there are only CharSequence
, Editable
, etc. I didn't find any keyCode
parameters.
try this
protected 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)) {
//here do what you want
}
return false; // very important
}
};
try this
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length()>0 && s.subSequence(s.length()-1, s.length()).toString().equalsIgnoreCase("\n")) {
//enter pressed
}
}
I think this is the better solution, because you can press 'Enter' in any place of your EditText field and not only at the end of line.
edittext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int st, int ct,
int af) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() < 1 || start >= s.length() || start < 0)
return;
// If it was Enter
if (s.subSequence(start, start + 1).toString().equalsIgnoreCase("\n")) {
// Change text to show without '\n'
String s_text = start > 0 ? s.subSequence(0, start).toString() : "";
s_text += start < s.length() ? s.subSequence(start + 1, s.length()).toString() : "";
edittext.setText(s_text);
// Move cursor to the end of the line
edittext.setSelection(s_text.length());
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With