我有一个包含编辑文本的片段。按下编辑文本时,将显示键盘。按下上角的“保存”按钮时,应用程序将返回上一个片段,但键盘仍然存在。
我希望在导航到上一个片段时隐藏键盘。
请注意,我尝试了这个解决方案:Close/hide the Android Soft Keyboard。
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myView.getWindowToken(), 0);
我尝试在onCreate方法的两个片段中使用它。
我还尝试在布局中隐藏软键盘:
android:windowSoftInputMode="stateAlwaysHidden"
不幸的是,这些都没有奏效。
我会张贴一些照片,但我还没有足够的名声。我会感激任何建设性的帮助和意见,不要忘记“聪明的人可以从愚蠢的问题中学到更多,而不是傻瓜可以从明智的答案中学习。” :)
此致,亚历山德拉
将隐藏键盘的代码放在“保存按钮”中单击监听器,并使用此方法隐藏键盘:
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);
}
}
在片段或活动中隐藏键盘的最简单方法
解决方案:1
//hide keyboard
public static void hideKeyboard(Context ctx) {
InputMethodManager inputManager = (InputMethodManager) ctx
.getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
View v = ((Activity) ctx).getCurrentFocus();
if (v == null)
return;
inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
解决方案:2
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
public 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);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 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 for Java code。