弹出框关闭后键盘未自动隐藏

3
我有一个用于显示地图的碎片(fragment)。从这个碎片中,我打开了另一个对话框碎片(dialog fragment),其中包含一个editText。当我点击editText时,键盘弹出,但是如果我在没有先关闭键盘的情况下关闭对话框碎片,那么对话框碎片会像应该关闭一样,但是键盘仍然保持打开状态。在再次触摸任何地方后,键盘才会关闭。我如何在关闭对话框碎片时关闭键盘?
我已经尝试过:在activity中使用android:windowSoftInputMode="stateAlwaysHidden"
也尝试了:
InputMethodManager imm =
                (InputMethodManager) messageEditTxt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive())
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

在`onDismiss`函数中。
3个回答

1
我曾遇到同样的问题,发现它与清单文件中定义的 windowSoftInput 有关。在从活动中移除 android:windowSoftInputMode="stateHidden" 后,问题得以解决。

1

试试这个

public static void hideSoftKeyboard(Context context, View view) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) context.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    view.getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

使用
hideSoftKeyboard(getActivity(), getView())

0
只需将此代码放入您的全局类中,您就可以在任何地方访问它。
public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        //Find the currently focused view, so we can grab the correct window token from it.
        View view = activity.getCurrentFocus();
        //If no view currently has focus, create a new one, just so we can grab a window token from it
        if (view == null) {
            view = new View(activity);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

对于活动:

GlobalClass.hideSoftKeyborad(MainActivity.this);

对于片段-

GlobalClass.hideSoftKeyborad(getActivity);

已经尝试过但不起作用......我传递了活动上下文,但没有解决方案。 - Bipin Tiwari

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