您的位置:首页 > 移动开发 > Android开发

Android 软键盘的监听(监听高度,是否显示)

2015-07-29 15:04 459 查看
Android官方本身没有提供一共好的方法来对软键盘进行监听,但我们实际应用时,很多地方都需要针对软键盘来对UI进行一些优化。

以下是整理出来的一个不错的方法,大家可以使用。

不过要注意的是,由于是使用ViewTreeObserver来进行监听,所以每次layout有所改变的话,都会触发,所以listner里面如果有改变layout的方法的话,要注意不要陷入无限触发循环了,这时需要加入一些标记值来规避,这个可以参考代码注释

public class SoftKeyboardUtil {
    public static final String TAG = "SoftKeyboardUtil";

    public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {
        final View decorView = activity.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHeight = rect.bottom - rect.top;
                int height = decorView.getHeight();
                boolean hide = (double) displayHeight / height > 0.8;
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "DecorView display hight = " + displayHeight);
                    Log.d(TAG, "DecorView hight = " + height);
                    Log.d(TAG, "softkeyboard visible = " + !hide);
                }

                listener.onSoftKeyBoardChange(height - displayHeight, !hide);

            }
        });
    }

    /**
     * Note: if you change layout in this method, maybe this method will repeat because the ViewTreeObserver.OnGlobalLayoutListener will repeat So maybe you need do some handle(ex: add some flag to avoid repeat) in this callback
     * 
     * Example:
     * 
     * private int previousHeight = -1; private void setupKeyboardLayoutWhenEdit() { SoftKeyboardUtil.observeSoftKeyBoard(this, new OnSoftKeyboardChangeListener() {
     * 
     * @Override public void onSoftKeyBoardChange(int softkeybardHeight, boolean visible) { if (previousHeight == softkeybardHeight) { return; } previousHeight = softkeybardHeight; //code for change layout } }); }
     * 
     * 
     * 
     */
    public interface OnSoftKeyboardChangeListener {
        void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: