问题
I want to recognize which key on the keyboard is pressed in Android. I have searched a lot but I haven't reached to correct answer yet. Some posts in StackOverflow that I have seen them but they don't answer me are here:
How to listen the keypress in the soft keyboard?
Android - Get keyboard key press
how to find which key is pressed in android?
回答1:
You can use the TextWatcher api provided by Android.
Here a code snippet from one of the answer:
field1.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) {
if (s.length() != 0)
field2.setText("");
}
});
field2.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) {
if (s.length() != 0)
field1.setText("");
}
});
EDIT 1
Here's the template for tracking which key was pressed on the keyboard:
editText.setOnKeyListener(new 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
}else if(keyCode == KeyEvent.KEYCODE_BACK) {
//this is for backspace
}
return false;
}});
来源:https://stackoverflow.com/questions/62788914/does-android-have-keyboard-listener-to-detect-which-key-is-pressed