隐藏键盘并单击按钮导航到新片段

时间:2019-10-28 13:54:11

标签: android kotlin input navigation

我目前正在努力结合导航和单击按钮时关闭键盘。 现在,我有一个使用R.id.action.actionname导航到新片段的按钮。当前是在onclick侦听器中设置的。如果用户导航到新片段,则键盘保持打开状态,这不应该发生。

我尝试使用下面的代码未成功

 val inputManager =
            activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val currentFocusedView = this.activity!!.currentFocus
        binding.idLoginButton.setOnClickListener() {

            if (currentFocusedView != null) {
                inputManager.hideSoftInputFromWindow(
                    currentFocusedView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
            Navigation.createNavigateOnClickListener(R.id.action_homeFragment_to_loginFragment)
        }

我也尝试过

Navigation.createNavigateOnClickListener(R.id.action_homeFragment_to_loginFragment)

的括号之间
  binding.idLoginButton.setOnClickListener()

这也不起作用。

2 个答案:

答案 0 :(得分:2)

将此代码放在您的Activity类中:-

override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    if (currentFocus != null) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
    }
    return super.dispatchTouchEvent(ev)
}

希望它能解决您的问题。

答案 1 :(得分:0)

如果没有焦点视图(例如,如果您只是更改片段可能会发生),那么其他视图将提供有用的窗口标记。

如果(view == null)view = new View(activity);这些是上述代码的替代方法;这些没有明确提及您的活动。

在片段类中:

view = getView()。getRootView()。getWindowToken(); 给定一个片段片段作为参数:

view = fragment.getView()。getRootView()。getWindowToken(); 从内容主体开始:

view = findViewById(android.R.id.content).getRootView()。getWindowToken();

并将此行添加到方法的末尾:

view.clearFocus();

更多信息: https://stackoverflow.com/a/17789187/9351811