如何在软键盘上检测KEYCODE_DEL?

时间:2016-04-21 18:37:36

标签: android string android-edittext android-softkeyboard

mMessageComposeUsernamesMultiAutoCompleteTextView,我想删除空格(如果它是我MultiAutoCompleteTextView的最后一个字符)或删除一个字(到最后" ",如果不是)。

代码:

mMessageComposeUsernames.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){
                String string = mMessageComposeUsernames.getText().toString();
                if (!string.substring(string.length() - 1).equals(" ")) {
                    if (string.contains(" ")) {
                        string = string.substring(0, string.lastIndexOf(" "));
                    } else {
                        string = "";
                    }
                }
                Log.i("string", string);
                mMessageComposeUsernames.setText(string);
            }
            return false;
        }
    });

问题是我在Logs没有得到任何内容,所以我认为onKey没有被执行...当KEYCODE_DEL被“按下”时,我怎么能做我想做的事情软键盘? :)

1 个答案:

答案 0 :(得分:0)

您可以使用下面的代码来实现您的想法:

 String yourstring1 = YourString.trim();
 if(!YourString.equals(yourstring1)){
     YourString = YourString.replace(YourString.substring(str.length()-1), "");
 }