在橫豎屏切換的時候會重新調用onCreate方法,可以使用以下方法禁止切換的過程中調用onCreate方法,如果你需要橫屏和豎屏使用不同的布局檔案,可能這種方式是不行的,經過我自己寫代碼測試,如果當前是豎屏,經過切換後它並不會使用橫屏的布局檔案,而是將豎屏的布局檔案使用在橫屏狀態下,不知道是我寫的不合適還是本來就這樣,希望和大家討論這個問題。通過查閱Android
API可以得知android:onConfigurationChanged實際對應的是Activity裡的onConfigurationChanged()方法。在AndroidManifest.xml中添加上訴代碼的含義是表示在改變螢幕方向、彈出軟體盤和隱藏軟鍵盤時,不再去執行onCreate()方法,而是直接執行onConfigurationChanged()。如果不申明此段代碼,按照Activity的生命週期,都會去執行一次onCreate()方法,而onCreate()方法通常會在顯示之前做一些初始化工作。所以如果改變螢幕方向這樣的操作都去執行onCreate()方法,就有可能造成重複的初始化,降低程式效率是必然的了,而且更有可能因為重複的初始化而導致資料的丟失。這是需要千萬避免的。
禁止調用onCreate方法:在Mainifest.xml的Activity元素中加入android:configChanges="orientation|keyboardHidden"屬性或者代碼中添加這個函數
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
我寫的測試程式:
package lzu.LandAndPortraintTest;import android.app.Activity;import android.content.pm.ActivityInfo;import android.content.res.Configuration;import android.os.Bundle;public class LandAndPortraintTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); printSentence(); } public void printSentence(){ System.out.println("printSentence"); } public void printPortraintSentence(){ System.out.println("printSentence Portraint"); } public void printLandscapeSentence(){ System.out.println("printSentence Landscape"); } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { printLandscapeSentence(); } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { printPortraintSentence(); } }}
layout-land下main.xml檔案:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout>
layout-port下main.xml檔案:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/app_name" /></LinearLayout>
values下strings.xml檔案:
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, LandAndPortraintTest!</string> <string name="app_name">LandAndPortraintTest</string></resources>
結果: