我正在尝试实现android主题(使用<style name="AppTheme" parent="Theme.AppCompat.DayNight">
)。
现在,从SettingActivity
,我很想选择主题。我已将SettingsActivity
定义为:
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
并且res/xml/root_preferences
具有:
<ListPreference
app:defaultValue="default"
app:entries="@array/themes_labels"
app:entryValues="@array/themes_color"
app:key="Theme"
app:title="@string/Theme"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
其中数组定义为:
<array name="themes_labels">
<item>"Default"</item>
<item>"Light"</item>
<item>"Dark"</item>
</array>
<string-array name="themes_color">
<item>"Default"</item>
<item>"Light"</item>
<item>"Dark"</item>
</string-array>
现在,问题是如何实现主题,即从首选项中获取值并实施。 This指南显示了一种非常简单的方法,如下所示:
int currentNightMode = configuration.uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
case Configuration.UI_MODE_NIGHT_NO:
// Night mode is not active, we're using the light theme
break;
case Configuration.UI_MODE_NIGHT_YES:
// Night mode is active, we're using dark theme
break;
}
但是问题是如何获取ListPreference的值并将其放入uiMode
。
请帮助。
//init sharedPreferences
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.apply();
//for saving String
editor.putString("theme", "day"); // here "theme" is key and "day" is value
editor.apply();
现在您可以像这样保存主题
//init SharedPreference here
//get SharedPreference
String sTheme = sharedPreferences.getString("theme", ""); // "theme" is key and second "" is default value
// now according to this value change theme
switch(sTheme){
// check and set theme here
setTheme(R.style.NightTheme);
}
// this is before setContent
setContentView(R.layout.your_activity);
您可以创建静态方法来执行所有这些操作,因为您必须在每个activity
中检查并设置主题。>
您还需要在Style
中创建多个res->styles.xml
希望这会有所帮助!