隐藏键盘并在单击按钮时导航到新片段
Hide keyboard and navigate to new fragment on button click
我目前正在努力将导航与单击按钮时关闭键盘结合起来。
现在我有一个使用 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()
这也没有用。
如果没有焦点视图(例如,如果您只是更改片段可能会发生),还有其他视图可以提供有用的 window 标记。
这些是上述代码的替代方案 if (view == null) view = new View(activity);这些未明确提及您的 activity.
片段内 class:
view = getView().getRootView().getWindowToken();
给定一个片段片段作为参数:
view = fragment.getView().getRootView().getWindowToken();
从您的内容正文开始:
view = findViewById(android.R.id.content).getRootView().getWindowToken();
并且还将这一行添加到方法的末尾:
view.clearFocus();
更多:
将此代码放入您的 Activity class :-
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)
}
希望它能解决您的问题。
我目前正在努力将导航与单击按钮时关闭键盘结合起来。 现在我有一个使用 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()
这也没有用。
如果没有焦点视图(例如,如果您只是更改片段可能会发生),还有其他视图可以提供有用的 window 标记。
这些是上述代码的替代方案 if (view == null) view = new View(activity);这些未明确提及您的 activity.
片段内 class:
view = getView().getRootView().getWindowToken(); 给定一个片段片段作为参数:
view = fragment.getView().getRootView().getWindowToken(); 从您的内容正文开始:
view = findViewById(android.R.id.content).getRootView().getWindowToken();
并且还将这一行添加到方法的末尾:
view.clearFocus();
更多:
将此代码放入您的 Activity class :-
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)
}
希望它能解决您的问题。