@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'函数,就是这样。 –