Does Android have keyboard listener to detect which key is pressed?

偶尔善良 提交于 2020-08-17 11:10:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!