一键切换主题:
切换主题的实现思路:
首先,使用的是setTheme(int id )切换主题,但是这个方法必须在onCreate方法中的所有的View被实例化之前调用,也就是在setContext之前调用。public class MainActivity extends ActionBarActivity {
TextView mTextView;
private int theme = 0;
private static final String TAG = "MainActivity";
@Override
protected void onResume() {
Log.d(TAG,"onResume");
super.onResume();
if(theme==Utils.getAppTheme(this)){
}else{
reload();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("theme",theme);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState==null){
theme=Utils.getAppTheme(this);
}else{
theme=savedInstanceState.getInt("theme");
}
setTheme(theme);
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate");
setContentView(R.layout.activity_main);
...
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id==R.id.action_switch_theme){
Utils.switchAppTheme(this);
reload();
return true;
}
return super.onOptionsItemSelected(item);
}
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);//不设置进入退出动画
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG,"onPause");
}
}