博客
我正在使用的方法。private void edgeToedge() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
EdgeToEdge.enable(this);
WindowInsetsControllerCompat windowInsetsController =
ViewCompat.getWindowInsetsController(getWindow().getDecorView());
if (windowInsetsController == null) {
return;
}
windowInsetsController.setAppearanceLightNavigationBars(true);
WindowCompat.getInsetsController(getWindow(),getWindow().getDecorView())
.setAppearanceLightStatusBars(true);
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
ViewCompat.setOnApplyWindowInsetsListener(toolbar, new OnApplyWindowInsetsListener() {
@NonNull
@Override
public WindowInsetsCompat onApplyWindowInsets(@NonNull View v, @NonNull WindowInsetsCompat insets) {
// Retrieve the insets for the system bars (status bar, nav bar, etc.)
Insets systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars());
// Update layout params: add a top margin equal to the status bar height.
ViewGroup.LayoutParams lp = v.getLayoutParams();
if (lp instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) lp;
marginParams.topMargin = systemBarsInsets.top;
v.setLayoutParams(marginParams);
}
// Alternatively, you can update padding if that better suits your design:
// v.setPadding(v.getPaddingLeft(), originalPaddingTop + systemBarsInsets.top,
// v.getPaddingRight(), v.getPaddingBottom());
return insets;
}
});
}
}
private void edgeToedge() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Ensure EdgeToEdge is correctly implemented or remove if not needed.
// EdgeToEdge.enable(this); // Uncomment if using a helper utility
WindowInsetsControllerCompat windowInsetsController =
ViewCompat.getWindowInsetsController(getWindow().getDecorView());
if (windowInsetsController == null) {
return;
}
// Set light status bar and light navigation bar appearance
windowInsetsController.setAppearanceLightNavigationBars(true);
windowInsetsController.setAppearanceLightStatusBars(true);
// Allow drawing behind system bars
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
// Apply window insets for toolbar margin
ViewCompat.setOnApplyWindowInsetsListener(toolbar, (v, insets) -> {
Insets systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars());
ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
marginParams.topMargin = systemBarsInsets.top; // Adjust for status bar height
v.setLayoutParams(marginParams);
return insets;
});
}
}