键盘高度

2020-03-14  本文已影响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);

}

上一篇下一篇

猜你喜欢

热点阅读