【问题标题】:How to implement android follow system night/dark mode?如何实现android跟随系统夜间/黑暗模式?
【发布时间】:2020-06-28 09:06:14
【问题描述】:

我已在我的应用程序中设置了 LightDark 模式及其工作。

但我还想添加一个选项,让应用遵循系统设置的模式。所以用户可以在三个选项中进行选择。

我尝试过,但没有成功。我想添加单选按钮来切换到浅色、深色、跟随系统模式。

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


【解决方案1】:

有一个选项可以做到这一点:AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);

【讨论】:

  • 谢谢我得到了这个工作,但我无法改变状态和导航栏的颜色,例如在浅色/白天主题白色状态和导航栏以及在黑暗/夜间主题黑色状态和导航栏上
  • 你必须重组你的主题才能做到这一点。请参阅ataulm.com/2020/04/30/refactoring-themes-with-style.html,然后查看 GitHub.com/ataulm/android 示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 2014-12-12
  • 2021-10-24
相关资源
最近更新 更多