Android獲取螢幕寬高,狀態列寬高,actionbar寬高,layout寬高,導航欄高度的方法彙總
看這個部落格你可以知道
獲取螢幕寬高,狀態列寬高,actionbar寬高,layout寬高,導航欄(虛擬按鍵欄)高度的方法
目錄順序為
程式碼測試的機型
狀態列高度
actionbar高度
螢幕高度
導航欄(虛擬按鍵欄)高度
layout寬高
總結
程式碼測試的機型:小米8青春版
這裡我們用的是小米8青春版手機測試(劉海屏)
小米8青春版螢幕px為1080*2280,相當於360*760dp
//獲取狀態列 private int getStatusBarHeight() { Class<?> c = null; Object obj = null; Field field = null; int x = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); return getResources().getDimensionPixelSize(x); } catch (Exception e1) { Log.d(TAG, "get status bar height fail"); e1.printStackTrace(); return 75; } } Log.i(TAG, "onCreate: "+getStatusBarHeight());
上面的是獲取狀態列方法,獲得狀態列的高度(px)
因為這裡用的小米手機是劉海屏,狀態列為20dp,通常手機螢幕的狀態列高度為25dp
dp=60/3=20dp
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Log.i(TAG, "onPause: "+statusBarHeight);
上面的是第二種獲取狀態列高度的方法(px)
P.s.該方法寫在onCreate()中不可以,會獲取到0
dp=60/3=20dp
//第一種獲取方法
int actionBarHeight = getSupportActionBar().getHeight();
//第二種獲取方法
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
上面是兩種獲取Actionbar高度的方法(px)
dp=168/3=56dp
P.s.該方法寫在onCreate()中不可以,會獲取到0
int screenWidth,screenHeight; WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); screenWidth = display.getWidth(); screenHeight = display.getHeight(); Log.i(TAG, "onCreate: "+screenWidth+","+screenHeight); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenWidth2 = dm.widthPixels; int screenHeight2 = dm.heightPixels; Log.i(TAG, "onCreate: "+screenWidth2+","+screenHeight2);
這是兩種獲取螢幕寬高的方法,單位為px
(獲取到的螢幕為狀態列+actionbar+頁面內容)
(不包含虛擬按鍵欄)
因為小米8青春版底部為虛擬按鍵欄,所以虛擬按鍵欄高度為2280-2150px=130px=43.3dp
//獲取虛擬按鍵欄高度
public static int getNavigationBarHeight(Context context, boolean b) {
int result = 0;
//是否純在虛擬按鍵欄(導航欄)
if (b) {
Resources res = context.getResources();
int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
}
return result;
}
上面是獲取虛擬按鍵欄(導航欄)高度的方法(px)
dp=130px/3=43.3dp
private ConstraintLayout constraintLayout;
constraintLayout=findViewById(R.id.screen_test);
constraintLayout.measure(0,0);
Log.i(TAG,"onCreate:"+constraintLayout.getMeasuredHeight()+","+constraintLayout.getMeasuredWidth());
上面是獲取layout寬高的方法(px) ,這裡用一個約束佈局寬高都設定match_parent
P.s.該方法寫在onCreate()中不可以,會獲取到0
高dp=1922px/3=640.7dp
寬dp=1080px/3=360dp
注意點:儘量別在oncreate中獲取各類高度,因為在Android介面建立過程中,容易讀取不到寬高,會出現0的情況
總結:小米8青春版手機介面高度:
狀態列(StatusBar) 60px=20dp
ActionBar(標題欄) 168px=56dp
頁面內容 1922px=640.7dp
虛擬按鈕欄(導航欄) 130px=43.3dp
共計2280px=760dp
___________________________________分割線______________________________________
再用我自己的華為P10 plus真機測試一下螢幕高度
自己平時用的華為P10 plus, 解析度為1440*2560px,dp為360*640dp
狀態列(StatusBar) 24dp
ActionBar(標題欄) 56dp
頁面內容 560dp
高度共計640dp