Android 实现夜间模式

时间:2021-10-26 10:20:18

方法1

建一个 value-night 的文件夹,colors.xml如下:

<resources>
<color name="colorPrimary">#7D4112</color>
<color name="colorPrimaryDark">#7D4112</color>
<color name="colorAccent">#1F1F1F</color>
</resources>
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {

int id = menuItem.getItemId();

switch (id) {
case R.id.nav_setting:
Toast.makeText(this, "夜间模式", Toast.LENGTH_LONG).show();
if (isNightMode) {
uiManager.enableCarMode(0);
uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
isNightMode = !isNightMode;
} else {
uiManager.disableCarMode(0);
uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
isNightMode = !isNightMode;
}
return true;
default:
return true;
}
}

Android 实现夜间模式
但是这种方法会开启车载模式
Android 实现夜间模式

在笔者的测试机(红米1s)中,这种方法会先退出应用,再启动应用已经是夜间模式

注意点

CardView 的背景色是app:cardBackgroundColor="?attr/windowBackground"设置,不是普通的android:background