Android 手机安全边距获取
时间: 2023-11-08 10:07:57 浏览: 271
获取手机屏幕尺寸的代码段.zip
Android 手机的安全边距是为了防止应用程序因为各种原因(比如系统栏、虚拟按键等)而被遮挡或者被挤压。下面是获取安全边距的方法:
1. 使用 ViewCompat 类的方法获取安全边距:
```
int[] safeInsets = ViewCompat.getInsetsController(view).getInsets(
WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
int topInset = safeInsets.top;
int bottomInset = safeInsets.bottom;
int leftInset = safeInsets.left;
int rightInset = safeInsets.right;
```
2. 使用 WindowInsets 类的方法获取安全边距:
```
View view = getWindow().getDecorView().getRootView();
WindowInsets insets = view.getRootWindowInsets();
int topInset = insets.getSystemWindowInsetTop();
int bottomInset = insets.getSystemWindowInsetBottom();
int leftInset = insets.getSystemWindowInsetLeft();
int rightInset = insets.getSystemWindowInsetRight();
```
需要注意的是,获取安全边距的方法需要在视图被添加到窗口之后才能正确地返回安全边距。
阅读全文