废话不多说直接上代码。
工具类:
public class KeyBoardShowListener {
private Context ctx;
public KeyBoardShowListener(Context ctx) {
this.ctx = ctx;
}
OnKeyboardVisibilityListener keyboardListener;
public OnKeyboardVisibilityListener getKeyboardListener() {
return keyboardListener;
}
public interface OnKeyboardVisibilityListener {
void onVisibilityChanged(boolean visible);
}
public void setKeyboardListener(final OnKeyboardVisibilityListener listener, Activity activity) {
final View activityRootView = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private boolean wasOpened;
private final int DefaultKeyboardDP = 100;
// From @nathanielwolf answer... Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);
private final Rect r = new Rect();
@Override
public void onGlobalLayout() {
// Convert the dp to pixels.
int estimatedKeyboardHeight = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());
// Conclude whether the keyboard is shown or not.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
boolean isShown = heightDiff >= estimatedKeyboardHeight;
if (isShown == wasOpened) {
return;
}
wasOpened = isShown;
listener.onVisibilityChanged(isShown);
}
});
}
}
在需要调用的地方直接调用就行
new KeyBoardShowListener(TemplatePartyActivity.this).setKeyboardListener(
new KeyBoardShowListener.OnKeyboardVisibilityListener() {
@Override
public void onVisibilityChanged(boolean visible) {
if (visible) {
et_post_title.setCursorVisible(true);
//软键盘已弹出
} else {
//软键盘未弹出
et_post_title.setCursorVisible(false);
}
}
}, TemplatePartyActivity.this);