赞
踩
Android在3.0之后,Activity引入了新的一个方法:recreate(),从字面意思就知道是重新创建Activity的,3.0+版本才可以使用。
/**
* 调用recreate方法重新创建Activity会比正常启动Activity多调用了onSaveInstanceState
* ()和onRestoreInstanceState()两个方法,onSaveInstanceState()会在onCreate方法之前调用。
* 所以可以在onCreate()方法中获取onSaveInstanceState()保存的Theme数据
*
* @description:
* @author ldm
* @date 2016-4-19 上午9:34:49
*/
public class MainActivity extends Activity implements OnClickListener {
private Button recreate;
private int mCurrentTheme;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 从onSaveInstanceState(Bundle outState)方法中保存的数据取出Theme
if (savedInstanceState != null) {
mCurrentTheme = savedInstanceState.getInt("mCurrentTheme");
// 切换Activity的Theme
switch (mCurrentTheme) {
case android.R.style.Theme_Holo_Light:
mCurrentTheme = android.R.style.Theme_Holo_Dialog;
break;
case android.R.style.Theme_Holo_Dialog:
mCurrentTheme = android.R.style.Theme_Holo;
break;
default:
mCurrentTheme = android.R.style.Theme_Holo_Light;
break;
}
setTheme(mCurrentTheme);
}
setContentView(R.layout.activity_main);
this.recreate = (Button) findViewById(R.id.recreate);
this.recreate.setOnClickListener(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("mCurrentTheme", mCurrentTheme);// 把当前Theme保存
}
@Override
public void onClick(View v) {
recreate();// 直接调用Activity的recreate()方法重启Activity
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。