Handle “Enter” key on Jelly Bean

谁说我不能喝 提交于 2019-12-02 07:11:24

问题


I'm making an application, in this application I have edit text. I want when user write some text in edit text end then press enter button, I want it call some command. This what i have been done. This is work in ICS, but when I try on other device (Jelly Bean) it doesn't work.

inputViaTextChatbot.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
                // hide the keyboard  
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                // process 
                getThis = inputViaTextChatbot.getText().toString();
                if (getThis!=null && getThis.length()>1) {  
                    try {
                    Log.v("Got This: ", getThis);
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    inputViaTextChatbot.setText("");  
                }
            }    
            return false;
        }
    });

can anyone help me to do this?


回答1:


This is a known bug that makes the Enter key not be recognized on several devices. A workaround to avoid it and make it work would be the following:

Create a TextView.OnEditorActionListener like this:

TextView.OnEditorActionListener enterKey = new TextView.OnEditorActionListener() {
  public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_GO) {
      // Do whatever you need
    }
    return true;
  }
};

Assuming your View is an EditText, for instance, you'd need to set it this way:

final EditText editor = (EditText) findViewById(R.id.Texto);
editor.setOnEditorActionListener(enterKey);

The final step to go is assigning the following attribute to the EditText:

android:imeOptions="actionGo"

This basically changes the default behavior of the enter key, setting it to the actionGo IME option. In your handler simply assign it the listener you've created and this way you'll have the enter key behavior.



来源:https://stackoverflow.com/questions/21834494/handle-enter-key-on-jelly-bean

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