我在使用 Android 开发人员指南的设置中有一个 listpreference,但是当用户选择浅色或深色时,应用程序主题不会改变。
根首选项:
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:id="@+id/list"
app:entries="@array/theme_entries"
app:entryValues="@array/theme_values"
app:key="theme"
app:title="@string/theme_title"
app:useSimpleSummaryProvider="true" />
<Preference
app:key="webpage"
app:title="Profile"
app:summary="View and edit your profile (opens in browser)">
<intent
android:action="android.intent.action.VIEW"
android:data="https://canvas.thelatinschool.org/profile" />
</Preference>
<Preference
android:id="@+id/notq"
app:key="notq"
app:title="Dark Mode"
app:summary="Dark Mode under construction for Android Pie and below"
>
</Preference>
数组:
<resources xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
<string-array name="theme_entries">
<item>Light</item>
<item>Dark</item>
<item>System default</item>
</string-array>
<string-array name="theme_values">
<item>light</item>
<item>dark</item>
<item>default1</item>
</string-array>
</resources>
还有我的 SettingsFragment 应该改变主题的地方:
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
PreferenceScreen screen = getPreferenceScreen();
final ListPreference listPreference = (ListPreference) findPreference("theme");
Preference preference = (Preference) findPreference("notq");
int api = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
if (api > 28) {
screen.removePreference(preference);
}
if (api < 29) {
screen.removePreference(listPreference);
}
listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
listPreference.setValue(newValue.toString());
theme = String.valueOf(listPreference.getEntry());
Log.d("debug", theme);
if (theme == "Light") {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
}
if (theme == "Dark") {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
}
if (theme == "System default") {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
}
return true;
}
});
}
}
日志输出给出值“Light”或“Dark”,但主题本身不会改变。我究竟做错了什么?
此外,我正在尝试为 Android 9 及更低版本的深色主题实现创建另一个列表首选项,因此假设我的数组值相同,我必须在 SettingsFragment 中更改什么才能使其工作?