切换主题

来源:互联网 发布:淘宝客服一周工作总结 编辑:程序博客网 时间:2024/04/29 01:18

一键切换主题:

切换主题的实现思路:

  首先,使用的是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";@Overrideprotected void onResume() {  Log.d(TAG,"onResume");  super.onResume();  if(theme==Utils.getAppTheme(this)){  }else{     reload();  }}@Overrideprotected void onDestroy() {  super.onDestroy();  Log.d(TAG,"onDestroy");}@Overrideprotected void onSaveInstanceState(Bundle outState) {  super.onSaveInstanceState(outState);  outState.putInt("theme",theme);}@Overrideprotected 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);   ...}@Overridepublic 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;}@Overridepublic 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);}@Overrideprotected void onRestart() {  super.onRestart();  Log.d(TAG, "onRestart");}@Overrideprotected void onPause() {  super.onPause();  Log.d(TAG,"onPause");}}

0 1