How to make dark mode in every activity

﹥>﹥吖頭↗ 提交于 2020-12-15 07:13:23

问题


When I click night mode button it only apply in settings activity but other activities are not night mode.

This is xml
<Switch
        android:id="@+id/switch_button"
        android:layout_marginStart="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/night"/>

This is SettingsActivity
Switch aSwitch = findViewById(R.id.switch_button);
    aSwitch.setOnCheckedChangeListener((compoundButton, isChecked) -> {
        if (isChecked) {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }
        else
        {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
    });

And also when I close app and open again, night mode is not saved. How to do that?


回答1:


Try this:

  1. Make sure that the activities extends AppCompatActivity.

  2. Your theme must use Theme.AppCompat.DayNight therefore you should set your main theme or AppTheme to DayNight:

    <style name="AppTheme" parent="Theme.AppCompat.DayNight">
    
  3. Set the theme of your Activities in your AndroidManifest to:

    android:theme="@style/AppTheme"
    

or any theme that uses Theme.AppCompat.DayNight



来源:https://stackoverflow.com/questions/57421476/how-to-make-dark-mode-in-every-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!