原文发表于: , 大家没事可以去逛逛 (ง •̀_•́)ง
前言
在平时的 App 开发中, 免不了会遇到需要开发者隐藏软键盘的情况, 比如当在多个输入框填入个人基本信息, 最后有个保存按钮, 点击即可将个人基本信息保存, 这时就需要开发者编写代码去隐藏软键盘, 而不需要用户自己去手动隐藏, 这样大大提高 App 的用户体验。
网上大多数给的方法
public static void hideKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);}复制代码
而试验结果却是...
当软键盘显示了, 调用上述方法确实可以隐藏。 但是当软键盘已经隐藏了, 调用上述方法后又将重新显示。
不过! 解决办法还是有的
我在 StackOverflow 中逛了一圈, 最后试验出两个成功的方法, 如下:
public class SoftKeyboardUtil { /** * 隐藏软键盘(只适用于Activity,不适用于Fragment) */ public static void hideSoftKeyboard(Activity activity) { View view = activity.getCurrentFocus(); if (view != null) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * 隐藏软键盘(可用于Activity,Fragment) */ public static void hideSoftKeyboard(Context context, ListviewList) { if (viewList == null) return; InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); for (View v : viewList) { inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }}复制代码
有人可能会问 SoftKeyboardUtil 第二个方法的 List<View> viewList
参数是什么, viewList 中需要放的是当前界面所有触发软键盘弹出的控件。 比如一个登陆界面, 有一个账号输入框和一个密码输入框, 需要隐藏键盘的时候, 就将两个输入框对象放在 viewList 中, 作为参数传到 hideSoftKeyboard 方法中即可。
原理待以后慢慢发掘......