package com.future.dispatch.utils; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver; import java.util.LinkedList; import java.util.List; /*** * 监听键盘打开关闭 并回调高度 */ public class SoftKeyBroadManager implements ViewTreeObserver.OnGlobalLayoutListener{ public interface SoftKeyboardStateListener { void onSoftKeyboardOpened(int keyboardHeightInPx); void onSoftKeyboardClosed(int keyboardHeightInPx); } private final List listeners = new LinkedList(); private final View activityRootView; private int lastSoftKeyboardHeightInPx; private boolean isSoftKeyboardOpened; public SoftKeyBroadManager(View activityRootView) { this(activityRootView,false); } public SoftKeyBroadManager(View activityRootView, boolean isSoftKeyboardOpened) { listeners.add(OneManager); this.activityRootView = activityRootView; this.isSoftKeyboardOpened = isSoftKeyboardOpened; activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(this); } public static int height_jp; @Override public void onGlobalLayout() { final Rect r = new Rect(); activityRootView.getWindowVisibleDisplayFrame(r); int rootHeight = activityRootView.getRootView().getHeight(); final int heightDiff = rootHeight - (r.bottom - r.top); if (!isSoftKeyboardOpened && heightDiff > 500) { // 如果高度超过500 键盘可能被打开 isSoftKeyboardOpened = true; height_jp = heightDiff; notifyOnSoftKeyboardOpened(heightDiff); } else if (isSoftKeyboardOpened && heightDiff < 500) { isSoftKeyboardOpened = false; notifyOnSoftKeyboardClosed(height_jp); } } 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(int h) { for (SoftKeyboardStateListener listener : listeners) { if (listener != null) { listener.onSoftKeyboardClosed(h); } } } public SoftKeyboardStateListener OneManager = new SoftKeyboardStateListener() { @Override public void onSoftKeyboardOpened(int keyboardHeightInPx) { activityRootView.setScrollY(keyboardHeightInPx); } @Override public void onSoftKeyboardClosed(int keyboardHeightInPx) { activityRootView.setScrollY(0); } }; }