美文网首页
键盘高度

键盘高度

作者: 炚風霁月 | 来源:发表于2020-03-14 12:58 被阅读0次

    //记录原始窗口高度

    private int mWindowHeight =0;

    private ViewTreeObserver.OnGlobalLayoutListenermGlobalLayoutListener =new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override

        public void onGlobalLayout() {

    Rect r =new Rect();

    //获取当前窗口实际的可见区域

            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);

    int height = r.height();

    if (mWindowHeight ==0) {

    //一般情况下,这是原始的窗口高度

                mWindowHeight = height;

    }else {

    if (mWindowHeight != height) {//https://www.jianshu.com/p/09456c2fceff

    //两次窗口高度相减,就是软键盘高度

                    int softKeyboardHeight =mWindowHeight - height;

    setBottom(softKeyboardHeight);

    }

    }

    }

    };

    private void setListenerToRootView() {

    final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);

    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override

            public void onGlobalLayout() {

    boolean mKeyboardUp = isKeyboardShown(rootView);

    if (mKeyboardUp) {

    }else {

    setBottom(0);

    }

    }

    });

    }

    private void setBottom(int keyboardHeight) {

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)btn_bottom.getLayoutParams();

    params.bottomMargin = keyboardHeight;

    btn_bottom.setLayoutParams(params);

    }

    private boolean isKeyboardShown(View rootView) {

    final int softKeyboardHeight =100;

    Rect r =new Rect();

    rootView.getWindowVisibleDisplayFrame(r);

    DisplayMetrics dm = rootView.getResources().getDisplayMetrics();

    int heightDiff = rootView.getBottom() - r.bottom;

    return heightDiff > softKeyboardHeight * dm.density;

    }

    getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);

    @Override

    protected void onDestroy() {

    super.onDestroy();

    getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener);

    }

    相关文章

      网友评论

          本文标题:键盘高度

          本文链接:https://www.haomeiwen.com/subject/mjnvshtx.html