繁体   English   中英

如何实现 android 遵循系统夜间/黑暗模式?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM