Android监听键盘状态变化

如下监听键盘状态变化的代码摘自React native的键盘状态监听代码,

这个方法会影响部分性能,正常情况下可以忽略。


import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * Keyboard status monitor.
 *
 * usage:
 *
 * View view;//View must be had added to the View Tree
 *
 *
 * view.getViewTreeObserver().addOnGlobalLayoutListener(new KeyboardListener(view){
 *
 *     @Override
 *     public void keyboardStatusChanged(boolean keyboardDidShow, @Nullable KeyboardInfo params){
 *          if(keyboardDidShow){
 *              //showing or height changed
 *          }else{
 *              //hidden
 *          }
 *     }
 *
 * });
 */
public abstract class KeyboardListener implements ViewTreeObserver.OnGlobalLayoutListener {
    private int mKeyboardHeight = 0;
    private final Rect mVisibleViewArea = new Rect();
    private View view;
    private DisplayMetrics mDisplayMetrics;

    public KeyboardListener(View view) {
        if (view == null) {
            throw new NullPointerException("view is null");
        }

        mDisplayMetrics = view.getContext().getResources().getDisplayMetrics();
        this.view = view;
    }

    @Override
    public void onGlobalLayout() {
        View rootView = view.getRootView();
        if (rootView == null) {
            return;
        }
        rootView.getWindowVisibleDisplayFrame(mVisibleViewArea);
        final int heightDiff =
                mDisplayMetrics.heightPixels - mVisibleViewArea.bottom;
        if (mKeyboardHeight != heightDiff && heightDiff > 0) {
            // keyboard is now showing, or the keyboard height has changed
            mKeyboardHeight = heightDiff;

            KeyboardInfo keyboardInfo = new KeyboardInfo();
            keyboardInfo.screenX = mVisibleViewArea.left;
            keyboardInfo.screenY = mVisibleViewArea.bottom;
            keyboardInfo.width = mVisibleViewArea.width();
            keyboardInfo.height = mKeyboardHeight;

            sendEvent(true, keyboardInfo);
        } else if (mKeyboardHeight != 0 && heightDiff == 0) {
            // keyboard is now hidden
            mKeyboardHeight = heightDiff;
            sendEvent(false, null);
        }
    }

    private void sendEvent(boolean keyboardDidShow, @Nullable KeyboardInfo keyboardInfo) {
        keyboardStatusChanged(keyboardDidShow, keyboardInfo);
    }

    public abstract void keyboardStatusChanged(boolean keyboardDidShow, @Nullable KeyboardInfo params);

    public static class KeyboardInfo {
        /**
         * screen x pixle
         */
        public double screenY;
        public double screenX;
        public double width;
        public double height;
    }
}


你可能感兴趣的:(Android监听键盘状态变化)