判断键盘的显示情况
方式1:
private static boolean isSoftShowing(Activity mContext) {
//获取当前屏幕内容的高度
int screenHeight = mContext.getWindow().getDecorView().getHeight();
//获取View可见区域的bottom
Rect rect = new Rect();
//DecorView即为activity的顶级view
mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
//考虑到虚拟导航栏的情况(虚拟导航栏情况下:screenHeight = rect.bottom + 虚拟导航栏高度)
//选取screenHeight*2/3进行判断
return screenHeight*2/3 > rect.bottom;
}
方式2:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
boolean isOpen=imm.isActive();//isOpen若返回true,则表示输入法打开
隐藏软键盘
方式1:在清单文件的activity加入:
android:windowSoftInputMode= "stateAlwaysHidden"
方式2:java代码
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
方式3:在有些地方会发现方式2的方法没有作用:
public static void hideSoftInput(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (isSoftShowing(activity)) {
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
键盘显示方法
方式1:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
方式2:
public static void showSoftInput(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!isSoftShowing(activity)) {
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
备注:解释下toggleSoftInput()方法,如果输入法在窗口上已经显示,则隐藏,反之则显示,所以需判断键盘的状态。
网友评论