在Android 12中,Google推出了Material You设计语言,该设计语言允许用户对整个系统的颜色进行个性化设置。为了采用这一新特性,开发人员需要检测用户的主题设置并相应地更新应用程序的UI。
以下是实现主题检测的代码示例:
if (Build.VERSION.SDK_INT >= 31) {
WindowInsetsController controller = view.getWindowInsetsController();
if (controller != null) {
controller.addOnControllableInsetsChangedListener(
new WindowInsetsController.OnControllableInsetsChangedListener() {
@Override
public void onControllableInsetsChanged(WindowInsetsController controller,
int typeMask) {
if ((typeMask & WindowInsets.Type.systemBars()) != 0) {
int newStyle = context.getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK;
if (newStyle == Configuration.UI_MODE_NIGHT_YES) {
// update your UI with dark theme colors
} else {
// update your UI with light theme colors
}
}
}
});
}
}
此代码使用WindowInsetsController的addOnControllableInsetsChangedListener方法来检测当用户更改系统主题设置时,系统栏是否已准备好被重新绘制。如果是,那么可以获取当前主题设置并相应地更新应用程序的UI。