[英]How to implement android follow system night/dark mode?
我在我的應用程序及其工作中設置了明暗模式。
但我還想添加一個選項,讓應用程序遵循系統設置的模式。 因此用戶可以在三個選項中進行選擇。
我試圖這樣做,但沒有成功。 我想添加單選按鈕來切換到淺色、深色、跟隨系統模式。
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();
}
}
});
}
}
有一個選項可以做到這一點: AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
。
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.