当软键盘中的“完成”按钮被按下时,如何使EditText失去焦点?

30

我在xml中有7个EditText框。我使用OnFocusChangeListener读取edittext的值,并将该值用于计算。我想在软键盘上的完成按钮被点击时使edittext失去焦点,以便我可以获取edittext中的值。

5个回答

79

当从软键盘上的“完成”按钮点击时,调用EditTextclearFocus方法来使其失去焦点。做法如下:

调用EditTextclearFocus方法来使其失去焦点,示例代码:

myEditText.clearFocus();
editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //Clear focus here from edittext
             editText.clearFocus();
        }
    return false;
    }
});

同时在EditText的xml中添加android:imeOptions="actionDone"


7
如果没有其他可聚焦的视图,或者相同的视图是从顶部开始可以获得焦点的第一个视图,则 clearFocus 可能无法起作用。文档的注释如下: 当一个 View 清除焦点时,框架会尝试将焦点给予从顶部开始第一个可聚焦的 View。因此,如果这个 View 是从顶部开始可以获得焦点的第一个视图,那么与清除焦点相关的所有回调都将在被调用后触发,然后框架将把焦点放在这个视图上。 - Mateus Gondim
1
使用 android:imeOptions="actionSend" 不会清除焦点,即使您调用 editText.clearFocus();请确保使用 android:imeOptions="actionDone" - Esdras Lopez
1
这会清除焦点,但会覆盖标准行为以隐藏键盘。 - Carson Holzheimer
尽管这是一篇古老的帖子,但它仍然具有相关性。在早期,Android支持真正的翻盖键盘。Android上的软键盘很差,因此自然而然地开发了许多围绕硬键盘的API。setKeyListener等诱人的歌声仍然非常强大。但是这篇文章让我看到了光明。当我转换到基于上面代码的东西时,它像魔法般地工作。现在已经是2022年了! - Martin Dunsmuir

2
如果有人想知道如何一次性取消活动中所有内容的重点关注,他们可以将焦点设置在父布局(或其他任何布局)上。
findViewById(R.id.myLayout).requestFocus();

对我来说不起作用,请求后第一个EditText获得了焦点。 - norbDEV

0

ρяσѕρєя K答案的Kotlin版本:

editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        editText.clearFocus()
    }
    false
}

0

只是一个更完整的答案

//  This will change the ‘RETURN’ button in your the EditText’s soft keyboard to a ‘DONE’ button.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
//  Use the InputMethodManager to close the soft keyboard
editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //Clear focus here from edittext
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    return false;
    }
});

0

Kotlin,它对我有用:

main.clearFocus()

main 是一个根 ConstraintLayout


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