手记

android开发:获取键盘的高度(实测真实有效)

由于最近在做即时通讯,做类似于微信的点击键盘消失,弹出表情页面(表情页面的高度和键盘的高度一致),于是在网上看了好多android测键盘高度的代码,都多多少少有些问题,于是我自己进行重新编写,终于弄了一个比较ok的测量高度的代码。

//一个静态变量存储高度
public static int keyboardHeight = 0;
    boolean isVisiableForLast = false;
    ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = null;
    public void addOnSoftKeyBoardVisibleListener() {
        getKeyboradHeight();
        if(keyboardHeight>0){
            return;
        }
        final View decorView = getWindow().getDecorView();
        onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                //计算出可见屏幕的高度
                int displayHight = rect.bottom - rect.top;
                //获得屏幕整体的高度
                int hight = decorView.getHeight();
                boolean visible = (double) displayHight / hight < 0.8;
                int statusBarHeight = 0;
                try {
                    Class<?> c = Class.forName("com.android.internal.R$dimen");
                    Object obj = c.newInstance();
                    Field field = c.getField("status_bar_height");
                    int x = Integer.parseInt(field.get(obj).toString());
                    statusBarHeight = getContext().getResources().getDimensionPixelSize(x);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if(visible&&visible!= isVisiableForLast){
                    //获得键盘高度
                    keyboardHeight = hight - displayHight-statusBarHeight;
                    Logger.sl(Log.DEBUG,"MMSL",keyboardHeight);

                }
                isVisiableForLast = visible;
            }
        };
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
    }
3人推荐
随时随地看视频
慕课网APP