微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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 举报,一经查实,本站将立刻删除。