我想每次點擊按鈕「保存」時保存用戶使用sharedPreferences
選擇的主題,但有一些我明顯做錯了,但我看不到它。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;
}
}
}
你在MainActivity設置主題? – 2013-05-01 05:51:39