0

我在我的应用程序及其工作中设置了明暗模式

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

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

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();
                }
            }
        });

    }
}

4

1 回答 1

0

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

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
于 2020-07-22T21:39:56.630 回答