import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import java.util.LinkedList;
import java.util.List;
/**
* 监听键盘关闭打开
*/
public class SoftKeyboardStateHelper implements ViewTreeObserver.OnGlobalLayoutListener {
public interface SoftKeyboardStateListener {
void onSoftKeyboardOpened(int keyboardHeightInPx);
void onSoftKeyboardClosed();
}
private final List<SoftKeyboardStateListener> listeners = new LinkedList<SoftKeyboardStateListener>();
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 > 100) {
isSoftKeyboardOpened = true;
notifyOnSoftKeyboardOpened(heightDiff);
} else if (isSoftKeyboardOpened && heightDiff < 100) {
isSoftKeyboardOpened = false;
notifyOnSoftKeyboardClosed();
}
}
public void addSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.add(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();
}
}
}
}
在当前activity或者dialog设置为如下配置的情况下获取键盘高度,dialog依附的activity需要设置如下配置
<item name="android:windowSoftInputMode">adjustNothing</item>
当设置为adjustNothing后,键盘弹出后界面不会有任何动作,可以根据需求测量键盘高度后修改当前界面的UI的高度
当界面中有scrollview的时候activity如下配置
android:configChanges="orientation|keyboardHidden|screenSize" android:windowSoftInputMode="adjustResize|stateHidden"
键盘可以将scrollview底部的之外的布局顶上去 但是有可能会监听不到键盘的弹出事件
如果做如下配置
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
则可以监听到键盘弹出,但是底部布局不能自定顶上去,需要自己处理android 配合scrollview 解决键盘遮挡EditText的问题_ange_li的博客-CSDN博客_android scrollview 键盘遮挡