无法从设置菜单切换应用程序的主题。从“ else”块开始主题
SharedPreferences sharedPrefs;
final String CURRENT_THEME = "CURRENT_THEME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String theme = sharedPrefs.getString("CURRENT_THEME",null);
if(theme != null && theme.equals("light"))
{
setTheme(R.style.AppThemeLight);
}
else
{
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lightTheme:
SharedPreferences.Editor editor1 = sharedPrefs.edit();
editor1.putString(CURRENT_THEME, "light");
editor1.commit();
return true;
case R.id.darkTheme:
SharedPreferences.Editor editor2 = sharedPrefs.edit();
editor2.putString(CURRENT_THEME, "dark");
editor2.commit();
return true;}
答案 0 :(得分:0)
从选项菜单中选择主题后,对其进行更改。
并使用editor.apply()
代替editor.commit()
final String CURRENT_THEME = "CURRENT_THEME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
changeTheme();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lightTheme:
SharedPreferences.Editor editor1 = sharedPrefs.edit();
editor1.putString(CURRENT_THEME, "light");
editor1.apply();
changeTheme();
return true;
case R.id.darkTheme:
SharedPreferences.Editor editor2 = sharedPrefs.edit();
editor2.putString(CURRENT_THEME, "dark");
editor2.apply();
changeTheme();
return true;}
private void changeTheme(){
String theme = sharedPrefs.getString(CURRENT_THEME,"light");
if(theme != null && theme.equals("light"))
{
setTheme(R.style.AppThemeLight);
}
else
{
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
答案 1 :(得分:0)
SharedPreferences sharedPrefs;
最终字符串CURRENT_THEME =“ CURRENT_THEME”;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
changeTheme();
setContentView(R.layout.activity_main);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lightTheme:
SharedPreferences.Editor editor1 = sharedPrefs.edit();
editor1.putString(CURRENT_THEME, "light");
editor1.apply();
changeTheme();
return true;
case R.id.darkTheme:
SharedPreferences.Editor editor2 = sharedPrefs.edit();
editor2.putString(CURRENT_THEME, "dark");
editor2.apply();
changeTheme();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void changeTheme(){
String theme = sharedPrefs.getString(CURRENT_THEME,"light");
if(theme != null && theme.equals("light"))
{
setTheme(R.style.AppThemeLight);
}
else
{
setTheme(R.style.AppTheme);
}
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
}