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

新手上路,请多包涵

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

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

请注意,我试过这个解决方案: Close/hide the Android Soft Keyboard

 InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myView.getWindowToken(), 0);

我试图在 onCreate 方法中的两个片段中使用它。

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

 android:windowSoftInputMode="stateAlwaysHidden"

不幸的是,这些都不起作用。

我会张贴一些图片,但我还没有足够的声誉。我将不胜感激任何建设性的帮助和意见,并且不要忘记“智者从愚蠢的问题中学到的东西比傻瓜从明智的答案中学到的更多”。 :)

问候,亚历山德拉

原文由 Alexandra Alstanei 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 709
2 个回答

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

     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);
         }
     }

原文由 Silvia H 发布,翻译遵循 CC BY-SA 3.0 许可协议

科特林

对于 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)
    }
}

要从 Fragment 访问它,请将其命名为:

 hideKeyboard(activity as YourActivity)

感谢 Silvia H 的 Java 代码。

原文由 Yogesh Umesh Vaity 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题