在不同的API级别上,可以使用不同的方法来改变Android状态栏的颜色。以下是一些示例代码:
Window
类来设置状态栏颜色:// 在API级别为21及以上的设备上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, R.color.status_bar_color));
}
SystemBarTintManager
类来设置状态栏颜色:// 在API级别为19及以上的设备上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintColor(ContextCompat.getColor(this, R.color.status_bar_color));
}
WindowInsetsController
类来设置状态栏颜色:// 在API级别为30及以上的设备上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsetsController controller = getWindow().getInsetsController();
if (controller != null) {
controller.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
controller.setSystemBarsColor(ContextCompat.getColor(this, R.color.status_bar_color));
}
}
请注意,上述代码中的R.color.status_bar_color
应替换为您自己定义的状态栏颜色。