I have an "edittext" in my app, and I want to do things when certain characters are pressed on the soft keyboard. I have tried every which way and how stackOverflow suggests, however characters i.e a/A, b/B etc dont get detected. Enter and Del do however. After reading loads, Apparently I have to override the edittext class, according to an example on here, so I have done that. I am overriding the method here:
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_A) {
ZanyEditText.this.setRandomBackgroundColor();
return false;
}
return super.sendKeyEvent(event);
}
I also have tried overriding the standard edittext onKeyListener:
txtSMS.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
// this is for backspace
Toast.makeText(getApplicationContext(), "Del was pressed", Toast.LENGTH_SHORT).show();
}
if (keyCode == KeyEvent.KEYCODE_A) {
// this is for backspace
Toast.makeText(getApplicationContext(), "A was pressed", Toast.LENGTH_SHORT).show();
}
return false;
}
However in both cases on the Del is ever detected. how come I cant detect characters of the alphabet? They appear in the text box...
Thanks
I was having a similar issure, you need to use a TextWatcher and then detect what was the last character to be entered (using 'subSequence'). The use logic to determine delete was pressed or an a was entered, hope this helps
See code below:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
//this is the method that detects the last entry below
String c = s.subSequence(before, before + 1).toString();
//check for delete
if (before < s.length()) {
String c = s.subSequence(before, before + 1).toString();
//see if a was entererd
if (c == a) {
//a entered
}
} else {
//delete pressed
}
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
});