int mNavSize;publicintgetSoftInputHeight(){int mSoftInputHeight;int mScreenHeight = ScreenUtils.getScreenHeight(this);final View mDecorView =this.getWindow().getDecorView();
Rect rect =newRect();// Window可視區域座標(不包含狀態欄與底部導航欄高度,此時軟鍵盤已經升起)
mDecorView.getWindowVisibleDisplayFrame(rect);// 不建議用這種方式獲取軟鍵盤高度// int mDecorViewBottom = mDecorView.getBottom();// int mSoftInputHeight = Math.abs(mDecorViewBottom - rect.bottom);int diffSize = Math.abs(mScreenHeight - rect.bottom);if(mNavSize >0){// 如果導航欄可見
mSoftInputHeight = diffSize - mNavSize;}else{// 如果導航欄不可見
mSoftInputHeight = diffSize;}return mSoftInputHeight;}
屏幕工具類
publicfinalclassScreenUtils{/**
* Return the width of screen, in pixel.
*
* @return the width of screen, in pixel
*/publicstaticintgetScreenWidth(Context context){
WindowManager wm =(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);if(wm == null)return-1;
Point point =newPoint();if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
wm.getDefaultDisplay().getRealSize(point);}else{
wm.getDefaultDisplay().getSize(point);}return point.x;}/**
* Return the height of screen, in pixel.
*
* @return the height of screen, in pixel
*/publicstaticintgetScreenHeight(Context context){
WindowManager wm =(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);if(wm == null)return-1;
Point point =newPoint();if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
wm.getDefaultDisplay().getRealSize(point);}else{
wm.getDefaultDisplay().getSize(point);}return point.y;}}