关闭软键盘
View view = getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}```
##打开软键盘
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, 0);
}```
view必须是VISIBLE的EditText,如果不是VISIBLE的,需要先将其设置为VISIBLE。
http://blog.csdn.net/ccpat/article/details/46717573
参数 | 0 | SHOW_IMPLICIT | SHOW_FORCED |
---|---|---|---|
0 | T | T | T |
HIDE_IMPLICIT_ONLY | F | T | F |
HIDE_NOT_ALWAYS | T | T | F |
检查软键盘是否显示
/**
* 判断软键盘是否显示
*
* @param rootView 根View
* @return
*/
protected boolean isKeyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}```
##软键盘弹起和收起监听
final int MIN_KEYBOARD_HEIGHT_PX = 150;
final View decorView = getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private final Rect windowVisibleDisplayFrame = new Rect();
private int lastVisibleDecorViewHeight;
@Override
public void onGlobalLayout() {
// Retrieve visible rectangle inside window.
decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();
// Decide whether keyboard is visible from changing decor view height.
if (lastVisibleDecorViewHeight != 0) {
if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) {
// Calculate current keyboard height (this includes also navigation bar height when in fullscreen mode).
int currentKeyboardHeight = decorView.getHeight() - windowVisibleDisplayFrame.bottom;
// Notify listener about keyboard being shown.
llBottom.setVisibility(View.GONE);
} else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) {
// Notify listener about keyboard being hidden.
llBottom.setVisibility(View.VISIBLE);
}
}
// Save current decor view height for the next call.
lastVisibleDecorViewHeight = visibleDecorViewHeight;
}
});```