Recently, I was working on a project. I drew a custom View, XXdp from the bottom of the screen, and arranged the position of the custom View in the onLayout() callback method in the parent layout that occupied the full screen. The coordinate algorithm of the Y-axis is as follows:
val mViewYPosition = Utils.getScreenHeight() - mView.measureHeight - bottomMargin
The tool to obtain the height of the mobile phone screen is as follows:
private int sScreenHeight = 0 public static int getScreenHeight() { if (sScreenHeight ! = 0) { return sScreenHeight; } WindowManager wm = (WindowManager) mAppContext.getSystemService(Context.WINDOW_SERVICE); if (wm ! = null && wm.getDefaultDisplay() ! = null) { DisplayMetrics outMetrics = new DisplayMetrics(); Display display = wm.getDefaultDisplay(); display.getMetrics(outMetrics); switch (display.getRotation()) { case Surface.ROTATION_0: case Surface.ROTATION_180://fall through sScreenHeight = outMetrics.heightPixels; sScreenWidth = outMetrics.widthPixels; break; case Surface.ROTATION_90: case Surface.ROTATION_270://fall through sScreenHeight = outMetrics.widthPixels; sScreenWidth = outMetrics.heightPixels; break; } return sScreenHeight; } else { return 1080; }}Copy the code
The actual test found that the height of the custom View from the bottom was significantly inconsistent on different Android models.
Finally, through investigation, it is found that the screen height acquisition method of different models is different:
- For example, on xiaomi note3 (Android 9, physical navigation bar), screenHeight is the final screenHeight
- The mi 10’s final screenHeight is screenHeight + statusBarHeight + navigationBarHeight
Therefore, it is best to get the height of the current full-screen parent layout directly. Here are the wrong and correct ways:
- Wrong way
var totalScreenHeight = DeviceTool.getStatusBarHeight() + DeviceTool.getScreenHeight() + DeviceTool. GetNavigationBarHeight () / / wrong wayCopy the code
- Accurate way
Var totalScreenHeight = measuredHeight // The correct way to get measuredHeightCopy the code
Here is a quick command to check the screen resolution:
adb shell wm size
Print the following: