切换主题

一键切换主题:

切换主题的实现思路:

  首先,使用的是setTheme(int id )切换主题,但是这个方法必须在onCreate方法中的所有的View被实例化之前调用,也就是在setContext之前调用。
  我们使用Theme.AppCompat.Light.DarkActionBar 的主题样式来代替日间模式,使用Theme.AppCompat 的主题样式来代替夜间模式。


  因为setTheme()的特殊性,我们必须在点击切换主题时重新生成一次Activity并调用setTheme(int id).


  这是实现的代码,也是核心代码:


  public void reload() {
    Intent intent = getIntent();
    overridePendingTransition(0, 0);//不设置进入退出动画
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    overridePendingTransition(0, 0);
    startActivity(intent);
  }




  以下是源代码:
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");
}
}

你可能感兴趣的:(Android,Android,切换主题,夜间模式)