工具类
public class SoftKeyboardStateHelper implements ViewTreeObserver.OnGlobalLayoutListener {
public interface SoftKeyboardStateListener {
void onSoftKeyboardOpened(int keyboardHeightInPx);
void onSoftKeyboardClosed();
}
private static final int KEYBOARD_HEIGHT = DensityUtil.dip2px(context, 100);
private final List<SoftKeyboardStateListener> listeners = new LinkedList<>();
private final View activityRootView;
private int lastSoftKeyboardHeightInPx;
private boolean isSoftKeyboardOpened;
public SoftKeyboardStateHelper(View activityRootView) {
this(activityRootView, false);
}
public SoftKeyboardStateHelper(View activityRootView, boolean isSoftKeyboardOpened) {
this.activityRootView = activityRootView;
this.isSoftKeyboardOpened = isSoftKeyboardOpened;
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
@Override
public void onGlobalLayout() {
final Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
final int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if (!isSoftKeyboardOpened
&& heightDiff
> KEYBOARD_HEIGHT) { // if more than 100 pixels, its probably a keyboard...
isSoftKeyboardOpened = true;
notifyOnSoftKeyboardOpened(heightDiff);
} else if (isSoftKeyboardOpened && heightDiff < KEYBOARD_HEIGHT) {
isSoftKeyboardOpened = false;
notifyOnSoftKeyboardClosed();
}
}
public void setIsSoftKeyboardOpened(boolean isSoftKeyboardOpened) {
this.isSoftKeyboardOpened = isSoftKeyboardOpened;
}
public boolean isSoftKeyboardOpened() {
return isSoftKeyboardOpened;
}
public int getLastSoftKeyboardHeightInPx() {
return lastSoftKeyboardHeightInPx;
}
public void addSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.add(listener);
}
public void removeSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.remove(listener);
}
private void notifyOnSoftKeyboardOpened(int keyboardHeightInPx) {
this.lastSoftKeyboardHeightInPx = keyboardHeightInPx;
for (SoftKeyboardStateListener listener : listeners) {
if (listener != null) {
listener.onSoftKeyboardOpened(keyboardHeightInPx);
}
}
}
private void notifyOnSoftKeyboardClosed() {
for (SoftKeyboardStateListener listener : listeners) {
if (listener != null) {
listener.onSoftKeyboardClosed();
}
}
}
}
使用:
SoftKeyboardStateHelper softKeyboardStateHelper =
new SoftKeyboardStateHelper(findViewById(R.id.content_wrapper)); //最外层的layout
softKeyboardStateHelper.addSoftKeyboardStateListener(
new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
@Override
public void onSoftKeyboardOpened(int keyboardHeightInPx) {
}
@Override
public void onSoftKeyboardClosed() {
}
});
}
windowSoftInputMode = adjustNothing 时该控件不会生效
windowSoftInputMode = adjustPan 保证获得焦点的控件不被遮挡,另如果键盘弹出前编辑框在位置A ,点击编辑框时弹出键盘,且编辑框由动画上移至位置B,整个布局还是会向上推移保证位置A不被遮挡。
另华为安手机的安全键盘:在用户名和密码输入框之间相互切换时会自动切换输入法,导致打开键盘和关闭键盘在不当的时机多次调用;