在 Android 应用程序中将用户覆盖保留为默认日/夜模式的共享首选项

问题描述

在 Android 应用程序中设置日/夜模式的 recommended 方法是在 Application 类中。下面是扩展 Application 类的推荐代码,Owl 示例 code 类似:

public class MyApplication extends Application {
    public void onCreate() {
        super.onCreate();
        AppCompatDelegate.setDefaultNightMode(
            AppCompatDelegate.MODE_NIGHT_YES);
    }
}

无论用户偏好如何,上述代码将在每次应用启动时继续设置相同的日/夜模式。我想根据应用内设置 recommendation:

用户控制日/夜模式

建议提供一种方法用户覆盖 应用中的主题.... 一种常见的实现方式 将通过 ListPreference,在调用 setDefaultNightMode() 时 值发生变化。

这是我的代码,它使用 Application 类中的共享首选项来跨进程启动保持用户日/夜模式选择;但是从 Application 类访问共享首选项会稳定吗?

public class MyApplication extends Application {

    private static final String KEY = SettingsFragment.LIGHT_DARK_THEME;

    @Override
    public void onCreate() {
        super.onCreate();

        int nightMode;
        if (Q <= SDK_INT) {
            nightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYstem;
        } else {
            nightMode = AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
        }

        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        final String pos = preferences.getString(MyApplication.KEY,"");
        if (!pos.isEmpty()) {
            nightMode = Integer.valueOf(pos);
        }
        AppCompatDelegate.setDefaultNightMode(nightMode);
    }
}

来自 arrays.xml

<!-- Day/Night Preferences -->
<string-array name="DayNightListArray">
    <item>Day</item>
    <item>Night</item>
    <item>System setting</item>
</string-array>

<string-array name="DayNightListValues">
    <item>1</item>
    <item>2</item>
    <item>-1</item>
</string-array>

来自 root_preferences.xml

   <ListPreference
        app:defaultValue="-1"
        app:entries="@array/DayNightListArray"
        app:entryValues="@array/DayNightListValues"
        app:key="light_dark_theme"
        app:title="Day/Night Theme"
        app:useSimpleSummaryProvider="true" />

来自 SettingsFragment.java

// Key to the Day/Night ListPreference
public static final String LIGHT_DARK_THEME = "light_dark_theme";

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)