如何在 Android 应用程序上自动切换到暗模式? [英] How to automatically switch to dark mode on Android app?

查看:32
本文介绍了如何在 Android 应用程序上自动切换到暗模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个 Android 应用.我为黑暗模式制作了另一个用户界面.所以这就是我需要的;该应用程序将在当地时间自动切换到深色主题.例如,当太阳按当地时间下山时,应用程序将切换到黑暗模式.

I'm making an Android app. I made another UI for dark mode. So this is what I need; the app will switch to dark theme automatically by the local time. For example, when the sun goes down by the local time, app will be switched to dark mode.

或者另一种选择是按一天中的预设时间切换到暗模式.希望你明白我的问题.如果有人知道,请帮助我,如果可能的话,我更喜欢第一个选项.提前致谢.

Or another alternative is switching to dark mode by pre-setted time of the day. Hope you understand my problem. Please help me if anyone knows, I prefer the first option to do if it's possible. Thanks in advance.

推荐答案

快速方法:

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //restore preferences
        SharedPreferences settings0 = this.getSharedPreferences(PREFS_NAME, 0);
        lightMode = settings0.getBoolean("key0", true);

        //retrieve selected mode
        if (lightMode) {

            //light mode
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        } else {

            //dark mode
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }

        Switch switch0 = findViewById(R.id.Switch0);
        switch0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (darkMode) {

                    text = "Mode: light";

                    //light mode
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);

                    darkMode = false;

                } else {

                    text = "Mode: dark";

                    //dark mode
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);

                    darkMode = true;
                }

                //save music preferences
                SharedPreferences setting0 = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor0 = setting0.edit();
                editor0.putBoolean("key0", darkMode);
                editor0.apply();
            }
        });
}

这篇关于如何在 Android 应用程序上自动切换到暗模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆