恢复密钥添加新行而不是发送消息

时间:2017-10-23 20:17:56

标签: java android

我有这个代码用于触发用于发送消息的回车键。我正在使用Pixel XL测试我的应用程序而不是像普通手机那样发送消息,它出于某种原因添加了新行。任何想法如何克服这种废话?

 edittext.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    postComment();
                    return true;
                }
                return false;
            }
        });

2 个答案:

答案 0 :(得分:2)

使用IME选项可以更轻松地完成此操作。这允许您定义将替换键盘中的Enter键的特定操作,而不会处理键处理代码。

更新布局XML以添加imeOptions属性:

<EditText
    android:id="@+id/edittext"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:imeOptions="actionSend" />

然后,在Java代码中处理此特定事件:

EditText editText = (EditText) findViewById(R.id.edittext);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});

您可以在official Android documentation

中找到更多详细信息

答案 1 :(得分:1)

由于您使用的是Pixel XL(我认为它正在运行Android O),您可以尝试将setOnKeyListener替换为setOnEditorActionListener

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_MASK_ACTION) {
                postComment();
                return true;
            }

            return false;
        }
    });

您可以查看docs,了解有关使用setOnEditorActionListener代替setOnKeyListener的原因的详情。以下是描述原因的文档的简短引用:

  

对于软输入法上的任何键,您都不应该依赖于接收KeyEvent。特别是,默认软件键盘永远不会向任何针对Jelly Bean或更高版本的应用程序发送任何键事件,并且只会将删除和返回键的某些按键发送到针对Ice Cream Sandwich或更早版本的应用程序。请注意,无论版本如何,其他软件输入方法都可能永远不会发送关键事件。

实质上,不鼓励发送此类事件。使用IME选项。