我想在用户sharedPreferences
每次点击“保存”按钮时保存用户对主题的选择,但有些事情我显然做错了,但我看不到。
我的问题是,如果没有这些sharedPreferences
东西,我的应用程序会按照我想要的方式更改主题,并且没有问题。但是当我应用这些sharedPreferences
东西时,它会停止改变主题,而且它也没有保存。
我发表了一些评论,以帮助理解我想要完成什么以及在哪里完成。
这是我的设置类:
public class SettingsActivity extends Activity implements OnClickListener {
public static final String PREF_NAME = "MyPrefsFile";
public static int newTheme;
public final static int THEME_DARK = R.style.DarkTheme;
public final static int THEME_LIGHT = R.style.LightTheme;
public final static int THEME_COLORS = R.style.ColorsTheme;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Here is where I'm supposed to check the sharedPreferences then
// Set the theme option newTheme with the users last choice,
// and if there is
// a choice set the theme.
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
newTheme = settings.getInt("themeCustom", 0);
if(newTheme == THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(newTheme == THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(newTheme == THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
// Utils.onActivityCreateSetTheme(this);
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_settings);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = getIntent();
Intent main = new Intent(SettingsActivity.this,MainActivity.class);
switch (v.getId()) {
case R.id.button2:
newTheme = THEME_DARK;
finish();
startActivity(intent);
break;
case R.id.button3:
newTheme = THEME_LIGHT;
finish();
startActivity(intent);
break;
case R.id.button5:
newTheme = THEME_COLORS;
finish();
startActivity(intent);
break;
case R.id.button4:
// This button returns to the main activity without saving.
startActivity(main);
break;
case R.id.button6:
// this is the button save
SharedPreferences settings =
getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor edit;
edit = settings.edit();
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
startActivity(main);
break;
default:
break;
}
}
}