如何在Android中没有焦点的情况下隐藏软键盘?

7

我遇到了这样的情况,我检查软键盘是否打开,并且我想在代码中关闭它,但是当我使用下面的代码时,它无法关闭键盘,因为代码找不到任何焦点,但是键盘仍然打开,那么我该怎么隐藏它呢?

private void hideSoftKeyboard() {
    Activity activity = (Activity) sContext;
    View view = activity.getCurrentFocus();
    if (view != null) {

        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        //((Activity) sContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    } else {

            Log.i(sClassTag,"focus not found");

    }
}

View view = this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } - Charuක
1
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); - Charuක
可能是关闭/隐藏Android软键盘的重复问题。 - Charuක
太好了!对我有用,谢谢!也许你可以把这个移到答案里,然后我可以投票。 - newszer
好的..很高兴能帮忙 :)) - Charuක
使用此代码隐藏键盘 - Adil Mushtaq
3个回答

11

试着使用这个

你可以通过使用InputMethodManager,调用hideSoftInputFromWindow并传入包含你的焦点视图的窗口的标记,来强制Android隐藏虚拟键盘。

View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

这将强制隐藏键盘,无论在什么情况下。有些情况下,您可能需要将InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数传递,以确保仅在用户没有明确强制显示键盘(通过长按菜单)时才隐藏键盘。

或者这样做

InputMethodManager imm =(InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

你可以在这里找到更多细节。


0
InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);

1
始终要考虑为您的解决方案提供注释。您的代码是如何解决问题的? - Derviş Kayımbaşıoğlu

0

您可以使用这些扩展来切换键盘:

fun Context.showKeyboard() {
    val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}

fun Context.hideKeyboard() {
    val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY)
}

fun Context.toggleKeyboard() {
    val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    if (imm.isActive) {
        hideKeyboard()
    } else {
        showKeyboard()
    }
}

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