android - 处理 Jelly Bean 上的 "Enter"键

标签 android keyboard handle enter

我正在制作一个应用程序,在这个应用程序中我有编辑文本。我想当用户在编辑文本结束时写一些文本然后按回车按钮,我希望它调用一些命令。这就是我所做的。这在 ICS 中有效,但当我在其他设备 (Jelly Bean) 上尝试时,它不起作用。

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;
        }
    });

谁能帮我做这个?

最佳答案

这是一个已知错误,它会导致多个设备无法识别 Enter 键。避免它并使其工作的解决方法如下:

像这样创建一个 TextView.OnEditorActionListener:

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;
  }
};

例如,假设您的 View 是一个 EditText,您需要这样设置:

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

最后一步是将以下属性分配给 EditText:

android:imeOptions="actionGo"

这基本上改变了 enter 键的默认行为,将其设置为 actionGo IME 选项。在您的处理程序中,只需将您创建的监听器分配给它,这样您将拥有 enter key 行为。

关于android - 处理 Jelly Bean 上的 "Enter"键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834494/

相关文章:

android - "Developer error: this application is misconfigured"Google 使用列入白名单的客户端 ID 在 firebase 上登录

keyboard - Ergodox 和反引号/重音/重音(ErgoDox EZ Oryx 带 QWERTZ)

c - 如何枚举内核中指定进程的所有打开句柄(Windows)

c++ - 声明和初始化的问题

android - 来自 xml 的 ListFragment 布局

android - 为什么我不应该使用操作系统提供的菜单图标?

java - Android int 在 eclipse 中替换为 android.R.integer

android - Unity Android 键盘文本在白色背景上显示白色文本

Javascript 按键/向下/向上事件触发顺序

c++ - 句柄而不是指针的引用计数