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.java public 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()..... 添加如下屬性: <activity android:name="com.minimax.demo.MainActivity" android:label="@string/app_name" android:configChanges="keyboardHidden|orientation|screenSize" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 在添加屬性之後之後,打印的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()方法