在 Android 中使用 TextInputEditText 注册按键

Registering pressed keys with TextInputEditText in Android

我正在尝试捕获在 TextInputEditText(来自 Material Design)上按下了哪个键,尽管我按下了键盘上的任意键,但我无法进入 onKey 方法。有人可以帮我吗?

txtInputApo.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.i("onKey","true");
            if(event.getAction() == KeyEvent.ACTION_UP){
                switch (keyCode){
                    case KeyEvent.KEYCODE_SPACE:
                        String Espaces = txtInputApo.getText().toString().replaceAll(" ", "");
                        txtInputApo.setText(Espaces);
                        txtInputApo.setSelection(Espaces.length());
                        break;

                }
            }

            return false;
        }
    });

谢谢!

View.OnKeyListener 主要是为硬件输入而构建的。大多数时候,对于这种情况(监视和修改用户输入),最好使用 TextWatcher

您可以通过 TextWatcher:

来实现您想要的结果
    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String editableString = s.toString();
            if (editableString.contains(" ")) {
                final String spaceFreeString = editableString.replaceAll(" ", "");
                txtInputApo.setText(spaceFreeString);
                txtInputApo.setSelection(spaceFreeString.length());
            }
        }
    };
    txtInputApo.addTextChangedListener(watcher);