@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create: //run NoteActivity in new note mode
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_theme:
setTheme(R.style.Theme2);
setContentView(R.layout.activity_main);
Intent i = getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
// TODO: show settings activity
break;
}
return super.onOptionsItemSelected(item);
}
我在我的活動頂部有一個菜單項。我想用它在按下時更改主題。我想在用戶啓動該程序後執行此操作,並最終用於循環使用一系列不同的主題!現在我只想讓它與一個工作。我怎樣才能做到這一點?onCreate()後以編程方式更改主題
我的回答
主要活動
SharedPreferences pref;
SharedPreferences.Editor editor;
int check;
int newcheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
check = pref.getInt("x", 0);
if(check == 0){
setTheme(R.style.AppTheme);
}else{
setTheme(R.style.Theme2);
}
setContentView(R.layout.activity_main);
noteActivity = new NoteActivity();
mListNotes = (ListView) findViewById(R.id.main_listview);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create: //run NoteActivity in new note mode
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_theme:
pref = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
editor = pref.edit();
newcheck = pref.getInt("x",0);
if(newcheck == 0) {
newcheck = 1;
}else if(newcheck == 1){
newcheck = 0;
}
editor.clear();//clears the editor to avoid errors
editor.putInt("x",newcheck);//add in new int
editor.commit();//commit
//restart the activity
Intent i = getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();//close activity - avoid crash
startActivity(i);//start activity
//TODO show settings activity
break;
}
return super.onOptionsItemSelected(item);
}
那麼你現在面臨的問題是什麼?主題設置不正確? –
當我按下按鈕它不會改變主題。我在onCreate()方法中測試了它,所以主題設置正確。 – pewpew
爲什麼你要再次開始「活動」呢?你應該使用'setTheme'函數,就是這樣。 –