參考两篇文章:http://blog.youkuaiyun.com/watermusicyes/article/details/47392949
http://blog.youkuaiyun.com/droyon/article/details/21275797
recreate能够使用在日间/夜间模式的切换,那么调用recreate()函数将会运行哪些方法呢?
代码:
public class MainActivity extends FragmentActivity implements OnClickListener {
private Button btn;
private int mTheme;
private String THEME = "theme";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mTheme = savedInstanceState.getInt(THEME);
switchTheme(mTheme);
}
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
Log.e(MainActivity.class.getName(), "onCreate");
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.e(MainActivity.class.getName(), "onSaveInstanceState");
savedInstanceState.putInt(THEME, mTheme);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.e(MainActivity.class.getName(), "onRestoreInstanceState");
}
@Override
protected void onStart() {
super.onStart();
Log.e(MainActivity.class.getName(), "onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.e(MainActivity.class.getName(), "onResume");
}
private void switchTheme(int theme) {
switch (mTheme) {
case android.R.style.Theme_Holo_Light:
mTheme = android.R.style.Theme_Black_NoTitleBar;
break;
case android.R.style.Theme_Black_NoTitleBar:
mTheme = android.R.style.Theme_Holo_Light;
break;
default:
mTheme = android.R.style.Theme_Holo_Light;
break;
}
setTheme(mTheme);
}
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
recreate();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.testandroid.MainActivity" >
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="recreate" />
</RelativeLayout>
点击recreatebutton能够看到打印相关的信息:
能够看到这里调用recreate方法会比正常启动Activity多调用了onSaveInstanceState和onRestoreInstanceState。而且onSaveInstanceState在onCreate方法之前调用。
注意:(1)
if (savedInstanceState != null) {
mTheme = savedInstanceState.getInt(THEME);
switchTheme(mTheme);
}
这部分代码要在setContentView(R.layout.activity_main)代码之前调用,否则改变不了主题。
(2)recreate()方法是在Android3.0引入的,所以假设在3.0之前使用会出现错误。例如以下图所看到的: