//記錄原始窗口高度
private int mWindowHeight =0;
private ViewTreeObserver.OnGlobalLayoutListenermGlobalLayoutListener =new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
? ? public void onGlobalLayout() {
Rect r =new Rect();
//獲取當(dāng)前窗口實(shí)際的可見區(qū)域
? ? ? ? getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int height = r.height();
if (mWindowHeight ==0) {
//一般情況下欺栗,這是原始的窗口高度
? ? ? ? ? ? mWindowHeight = height;
}else {
if (mWindowHeight != height) {//http://www.reibang.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);
}