在Android新版本中,为了更好地支持屏幕边缘的交互和显示,引入了WindowInsets API。为了适配WindowInsets,你需要遵循以下步骤:
onCreate
或onCreateView
方法,并调用WindowInsetsControllerCompat
来获取和处理WindowInsets。@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WindowInsetsControllerCompat windowInsetsController = getWindow().getInsetsController();
if (windowInsetsController != null) {
// 设置WindowInsetsListener
windowInsetsController.setOnApplyWindowInsetsListener(new WindowInsetsControllerCompat.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
// 处理WindowInsets
return insets;
}
});
}
}
onApplyWindowInsets
方法中,你可以获取和处理不同类型的WindowInsets(如ContentInsets、SystemInsets和NavigationInsets)。例如,你可以调整布局以适应刘海屏、水滴屏等。@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
// 获取ContentInsets
Rect contentInsets = insets.getContentInsets();
// 获取SystemInsets
Rect systemInsets = insets.getSystemInsets();
// 获取NavigationInsets
Rect navigationInsets = insets.getNavigationInsets();
// 根据需要调整布局
// ...
return insets;
}
@RequiresApi
注解来检查设备是否支持WindowInsets API。@RequiresApi(api = Build.VERSION_CODES.R)
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
}
WindowInsetsCompat
类来处理WindowInsets。这个类提供了向后兼容的方法来获取和处理WindowInsets。if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// 使用WindowInsetsControllerCompat
} else {
// 使用WindowInsetsCompat
WindowInsetsCompat windowInsetsCompat = WindowInsetsCompat.from(insets);
Rect contentInsets = windowInsetsCompat.getContentInsets();
// ...
}
通过以上步骤,你可以适配Android新版本中的WindowInsets。