原文发表于:blog.csdn.net/qq_27485935 , 你们没事能够去逛逛 (ง •̀_•́)งjava
在平时的 App 开发中, 免不了会遇到须要开发者隐藏软键盘的状况, 好比当在多个输入框填入我的基本信息, 最后有个保存按钮, 点击便可将我的基本信息保存, 这时就须要开发者编写代码去隐藏软键盘, 而不须要用户本身去手动隐藏, 这样大大提升 App 的用户体验。ide
public static void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}复制代码
而试验结果倒是...spa
当软键盘显示了, 调用上述方法确实能够隐藏。 可是当软键盘已经隐藏了, 调用上述方法后又将从新显示。.net
我在 StackOverflow 中逛了一圈, 最后试验出两个成功的方法, 以下:3d
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, List<View> viewList) {
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 方法中便可。code
原理待之后慢慢发掘......cdn