Android:当按下Done键时,软键盘执行操作

82

我有一个 EditText。我希望在用户输入文本后,按下软键盘的 Done 键时,可以直接执行我在按钮单击事件中实现的一些搜索操作。


1
在这个评论中,使用Kotlin的更好方法:https://dev59.com/z2Ik5IYBdhLWcg3wfOSf#48810268 - Francesco Donzello
5个回答

213

试试这个

editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //do something
        }
    return false;
    }
});

20

试一试

它适用于DONERETURN

EditText editText= (EditText) findViewById(R.id.editText);
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {

                @Override
                public boolean onEditorAction(TextView v, int actionId,
                        KeyEvent event) {
                    if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                            || actionId == EditorInfo.IME_ACTION_DONE) {
                        // Do your action
                        return true;
                    }
                    return false;
                }
            });

0

在 Kotlin 中使用

viewBinding.editText.setOnEditorActionListener { view, actionId, event ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        //react to action
    }
    false
}

你也可以在“if”括号内返回true来消耗事件 - 这样当你按下完成键时,键盘就不会关闭


0

你捕获 KeyEvent 然后检查它的键码。 FLAG_EDITOR_ACTION 用于识别来自输入法的回车键,其回车键已被自动标记为“下一个”或“完成”

if (event.getKeyCode() == KeyEvent.FLAG_EDITOR_ACTION)
    //your code here

在这里找到文档链接

第二种方法

myEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    int result = actionId & EditorInfo.IME_MASK_ACTION;
    switch(result) {
    case EditorInfo.IME_ACTION_DONE:
        // done stuff
        break;
    case EditorInfo.IME_ACTION_NEXT:
        // next stuff
        break;
    }
 }
});

0

试一下

这将在键盘显示回车符号或下一个箭头符号的情况下都有效。

YourEdittextName.setOnEditorActionListener(new TextView.OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            if(actionId== EditorInfo.IME_ACTION_DONE||actionId==EditorInfo.IME_ACTION_NEXT)
            {
                //Perform Action here 
            }
            return false;
        }
    });

如果你遇到了红色的线,那么就按下alt+enter导入Keyevent和EditorInfo,然后所有的错误就会被解决了……


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接