EditText有时候会在Activity的布局上,有时候会在非activity的布局上,所以如果写法不对的话,想隐藏软键盘很有可能实现不了,下面是正确的写法,可以将其写入工具类
//显示软键盘
public static void showKeyBoard(EditText v) {
if (v == null) return;
v.requestFocus();
v.post(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
//imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//上面那句话也能显示软键盘,但是发现华为手机如果是密码输入框的话能弹出软键盘,但是弹出的不是华为安全键盘,会导致输入不进去内容,所以推荐用下面的写法,亲测有效,而且能适配所有手机,官方也推荐这么写,SHOW_IMPLICIT是指隐性的,非用户操作的
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}
}
});
}
//隐藏软键盘有两种写法,根据实际情况选择
//1 直接传入EditText,适用于非Activity的情况
public static void closeKeyBoard(View v) {
if (v == null) return;
v.clearFocus();
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
//2 传入当前Activity,适用于Activity的情况
public static void closeKeyBoard(Activity act) {
if (act == null || act.getCurrentFocus() == null) return;
InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(), 0);
}
}