试过hideSoftInputFromWindow不起作用,只有toggleSoftInput其作用,但是这个方法是:输入法隐藏的时候显示,输入法显示的时候隐藏。我的应用场景是dialogFragment关闭的时候要把输入法隐藏,如果输入法本身就是隐藏状态,那么输入法会显示出来,这样是不对的。所以要加一个判断输入法是否是显示状态(参考https://www.jianshu.com/p/2bdb4018b6d1)
private boolean isInputMethodShowing() {
//获取当前屏幕内容的高度
int screenHeight = getActivity().getWindow().getDecorView().getHeight();
//获取View可见区域的bottom
Rect rect = new Rect();
getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
return screenHeight - rect.bottom - getSoftButtonsBarHeight() != 0;
}
/**
* 底部虚拟按键栏的高度
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private int getSoftButtonsBarHeight() {
DisplayMetrics metrics = new DisplayMetrics();
//这个方法获取可能不是真实屏幕的高度
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
//获取当前屏幕的真实高度
getActivity().getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight) {
return realHeight - usableHeight;
}
else {
return 0;
}
}
然后隐藏输入法
//如果输入法在窗口上已经显示,则隐藏,反之则显示
private void hideSoftInputWindow(Context context) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if(isInputMethodShowing()) {
LogUtils.i("hideSoftInputWindow:");
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}