我想制作一个 SettingsActivity
让用户个性化应用程序的外观。
在此 Activity 中,用户可以选择将应用程序保持在“浅色主题”(例如,白色背景和黑色文本)或“深色主题”,相反颜色的灯光主题有利于夜间使用。
这怎么可能?
我正在考虑为每个主题在 xml 中创建不同的布局。
编辑
下图是 SettingsActivity
的示例,我想更改整个应用的外观,而不是单个 Activity 。
最佳答案
这就是我为我的应用所做的。我相信我的方法可以提供帮助。
在 styles.xml 中设置您的浅色和深色主题,如下所示:
<!-- Use this theme in Manifest by default -->
<style name="MyLightTheme" parent="Base.AppTheme.Light"></style>
<!-- Base light theme containing all styles -->
<style name="Base.AppTheme.Light" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
... Other styles
</style>
<!-- Use this to switch to Dark theme -->
<style name="MyDarkTheme" parent="Base.AppTheme.Dark"></style>
<!-- Base dark theme containing all styles -->
<style name="Base.AppTheme.Dark" parent="Theme.AppCompat">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
... Other styles
</style>
由于您是通过首选项控制主题更改,因此请在您的 PreferenceFragment 中注册一个首选项更改监听器。
PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);
实现onSharedPreferenceChanged():
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(getString(R.string.pref_key_nighttheme))) {
if (sharedPreferences.getBoolean(getString(R.string.pref_key_nighttheme), false)) {
// Night theme enabled
getActivity().setTheme(R.style.MyDarkTheme);
getActivity().getApplication().setTheme(R.style.MyDarkTheme);
darkTheme = true;
} else {
getActivity().setTheme(R.style.MyLightTheme);
getActivity().getApplication().setTheme(R.style.MyLightTheme);
darkTheme = false;
}
getActivity().recreate(); // This is important. It allows the theme change to take effect.
}
}
如果后退导航指向 MainActivity,请务必在 onResume() 中重新创建您的 MainActivity。
此外,在 onCreate() 中调用 super() 之前,您必须检查每个 Activity 中的当前主题。
isThemeDark = setDarkTheme(this);
setDarkTheme() 是我创建的一个助手,它通过 SharedPreference 检查当前主题。它检查是否需要更改主题。
public static boolean setDarkTheme(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isDarkTheme = prefs.getBoolean(context.getString(R.string.pref_key_nighttheme), false);
context.setTheme(SettingsActivity.darkTheme ? R.style.MyDarkTheme : R.style.MyLightTheme);
return isDarkTheme;
}
下面是夜间模式在我的应用程序中的工作方式 Newslet :
更新: Android 现在通过其 AppCompat DayNight Theme 正式支持夜间模式。 这是一个 tutorial同样。
关于android - 如何更新我创建多主题应用程序的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668263/