从片段导航到另一个片段时隐藏键盘

Ale*_*nei 31 keyboard android android-softkeyboard android-fragments

我有一个包含编辑文本的片段.按下编辑文本时,将显示键盘.按下上角的"保存"按钮时,应用程序将返回上一个片段,但键盘仍然存在.

我希望在导航到上一个片段时隐藏键盘.

请注意,我尝试了这个解决方案: 关闭/隐藏Android软键盘.

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myView.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

我尝试在onCreate方法的两个片段中使用它.

我还尝试在布局中隐藏软键盘:

android:windowSoftInputMode="stateAlwaysHidden"
Run Code Online (Sandbox Code Playgroud)

不幸的是,这些都没有奏效.

我会张贴一些照片,但我还没有足够的名声.我会感激任何建设性的帮助和意见,不要忘记"聪明的人可以从愚蠢的问题中学到更多,而不是傻瓜可以从明智的答案中学习." :)

此致,亚历山德拉

Sil*_*a H 89

将隐藏键盘的代码放在"保存按钮"中单击监听器,并使用此方法隐藏键盘:

    public static void hideKeyboard(Activity activity) {
        InputMethodManager inputManager = (InputMethodManager) activity
        .getSystemService(Context.INPUT_METHOD_SERVICE);

        // check if no view has focus:
         View currentFocusedView = activity.getCurrentFocus();
         if (currentFocusedView != null) {
             inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
         }
     }
Run Code Online (Sandbox Code Playgroud)


Yog*_*ity 16

科特林

对于 Kotlin,您可以将其用作顶级函数,只需将代码添加到单独的类中,例如Utils.kt.

fun hideKeyboard(activity: Activity) {
    val inputMethodManager =
        activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

    // Check if no view has focus
    val currentFocusedView = activity.currentFocus
    currentFocusedView?.let {
        inputMethodManager.hideSoftInputFromWindow(
            currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}
Run Code Online (Sandbox Code Playgroud)

要从 Fragment 访问它,请像这样调用它:

hideKeyboard(activity as YourActivity)
Run Code Online (Sandbox Code Playgroud)

感谢 Silvia H 提供 Java 代码。