【发布时间】:2020-06-28 09:06:14
【问题描述】:
我已在我的应用程序中设置了 Light 和 Dark 模式及其工作。
但我还想添加一个选项,让应用遵循系统设置的模式。所以用户可以在三个选项中进行选择。
我尝试过,但没有成功。我想添加单选按钮来切换到浅色、深色、跟随系统模式。
Here's what I have tried
public class setting extends AppCompatActivity {
private Switch darkMode;
Button autoButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darktheme);
}
else {
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Settings");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitleTextAppearance(this, R.style.Font);
darkMode = (Switch) findViewById(R.id.darkModeSwitch);
autoButton = (Button) findViewById(R.id.autoButton);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
darkMode.setChecked(true);
}
darkMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getDelegate().applyDayNight();
recreate();
//restartApp();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
recreate();
// restartApp();
}
}
});
}
}
【问题讨论】:
-
在这里您可以找到问题的答案stackoverflow.com/questions/55787035/…
-
我想添加一个选项来“遵循系统范围的主题”,它是在 android 10 中正式引入的,如果设置可以更改为亮/暗模式,具体取决于系统中的设置。
标签: java android android-theme android-dark-theme android-night-mode