Activity在横竖屏切换的时候会重新走生命周期的方法,这样做的话会导致一些问题 比如我们在界面上录入的一些数据,但因为重新走了生命周期的方法onCreate()方法,这样就会导致前功尽弃,所以就想办法,在横竖屏切换的时候不能让其重新OnCreate(),Android中我们可以在清单文件中对应的Activity使用如下的属性 android:configChanges="keyboardHidden|orientation|screenSize" 这样就可以避免此类事情的发生。下面是示例代码:
package com.minimax.demo;import android.os.Bundle;import android.app.Activity;import android.view.Menu;///Activity横竖屏切换/src/com/minimax/demo/MainActivity.javapublic class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("onCreate()....."); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); System.out.println("onStart()....."); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); System.out.println("onResume()....."); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); System.out.println("onPause()....."); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); System.out.println("onStop()....."); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); System.out.println("onDestroy()....."); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); System.out.println("onRestart()....."); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }}在没有添加对应的属性之前,我们切换横竖屏之后打印的Log日志如下:04-22 21:50:51.954: I/System.out(24476): onCreate().....04-22 21:50:51.964: I/System.out(24476): onStart().....04-22 21:50:51.964: I/System.out(24476): onResume().....04-22 21:50:56.524: I/System.out(24476): onPause().....04-22 21:50:56.524: I/System.out(24476): onStop().....04-22 21:50:56.524: I/System.out(24476): onDestroy().....04-22 21:50:56.614: I/System.out(24476): onCreate().....04-22 21:50:56.614: I/System.out(24476): onStart().....04-22 21:50:56.614: I/System.out(24476): onResume().....添加如下属性:在添加属性之后之后,打印的Log日志如下:04-22 21:52:25.984: I/System.out(30283): onCreate().....04-22 21:52:25.984: I/System.out(30283): onStart().....04-22 21:52:25.994: I/System.out(30283): onResume().....无论如何我们切换横竖屏,都不会重新走onCreate()方法