參考 http://blog.csdn.net/tangzhilu/article/details/7399988
MainActivity 代碼
package com.example.configchangesample; import android.os.Bundle; import android.app.Activity; import android.content.res.Configuration; import android.util.Log; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { TextView textView1; String TAG = "configchangesample"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView1 = (TextView)this.findViewById(com.example.configchangesample.R.id.textView1); textView1.setText("init"); Log.i(TAG, "onCreate"); } @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; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); textView1.setText("onConfigurationChanged"); Log.i(TAG, "onConfigurationChanged:" + newConfig.orientation); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){ textView1.setText("ORIENTATION_LANDSCAPE"); } else { textView1.setText("ORIENTATION_PORTRAIT"); } } }
如果是 如下的配置
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.configchangesample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.configchangesample.MainActivity" android:label="@string/app_name" android:configChanges="orientation|screenSize" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
在android 4.2.2 真機 和 android 2.3.5 真機驗證,onConfigurationChanged 會被執行。
如果 android:configChanges="orientation|screenSize" 改為 android:configChanges="orientation"
在android 4.2.2 真機上驗證,onConfigurationChanged 不會被執行。
在android 2.3.5 真機上驗證,onConfigurationChanged 會被執行。
去掉 android:targetSdkVersion="18" 並且 android:configChanges="orientation"
在android 4.2.2 真機 和 android 2.3.5 真機驗證,onConfigurationChanged 會被執行。
另外,
1.記得在手機上打開自動轉屏的開關
2.測試發現, 轉屏時,無論如何 onCreate 不會被觸發。
網上的資料 加上keyboardHidden后onCreate 不會被觸發,不加就會觸發,這個解釋貌似站不住腳。
3. 反正記得一點,如果設置了android:targetSdkVersion ,記得加上screenSize
解釋比較羅嗦,點擊這里查看 http://developer.android.com/guide/topics/manifest/activity-element.html