1、默认配置
切换横竖屏执行onCreate(),重新加载。
2、切换时可以在onRetainNonConfigurationInstance保存数据 ,并在onCreate中 用getLastCustomNonConfigurationInstance();方法恢复数据。
@Override
protected void onCreate(Bundle savedInstanceState) {
Logger.d("onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UserDate userDate = (UserDate) getLastCustomNonConfigurationInstance();
if(userDate!=null)
Logger.i(userDate.toString());
else{
Logger.i("userDate == null");
}
}
@Override
public Object onRetainCustomNonConfigurationInstance() {
UserDate userDate = new UserDate();
Logger.i(userDate.toString());
return userDate;
}
3、不重启Activity
Andorid 3.2以前的SDK可以使用如下配置android:configChanges="orientation|keyboardHidden",而Adnroid 3.2以后的SDK必须添加screenSize属性,具体如下android:configChanges="keyboardHidden|orientation|screenSize"。然后在复写onConfigurationChanged(Configuration newConfig),这样每次切换时就不会执行onCreate,转而回调onConfigurationChanged方法
public void onConfigurationChanged(Configuration newConfig) {
int mCurrentOrientation = getResources().getConfiguration().orientation;
if( mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
// If current screen is portrait
setContentView(R.layout.mainP);
findViewsSetListensers();
}else if( mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
//If current screen is landscape
setContentView(R.layout.mainL);
//注意,这里删除了init(),否则又初始化了,状态就丢失
findViewsSetListensers();
}
}
引用连接