隨便搜一篇關於activity在橫豎屏切換後生命週期的執行過程你可能會看到如下答案:
1、不設置 Activity 的 android:configChanges 時,切屏會重新調用各個生命週期,
切橫屏時會執行一次,切豎屏時會執行兩次
2、設置 Activity 的 android:configChanges="orientation" 時,
切屏還是會重新調用各個生命週期,切橫、豎屏時只會執行一次
3、設置 Activity 的 android:configChanges="orientation|keyboardHidden" 時,
切屏不會重新調用各個生命週期,只會執行 onConfigurationChanged 方法
4、注意:還有一點,非常重要,一個 Android 的變更細節!當 API >12 時,
需要加入 screenSize 屬性,否則屏幕切換時即使你設置了 orientation 系統也會重建 Activity !
記得在學校學習android的時候,老師就這麼說過,我也就這麼記住了。然兒最近在整理面試資料的時候,看到這題,想到爲什麼切豎屏會執行兩次呢??於是我又寫了代碼來測試...發現這個答案不一定對...
一、不設置 android:configChanges="orientation" 情況下
Activity代碼如下:
/**
* Created by fySpring
* Date: 2020/4/12
* To do:
*/
class ActivityA : AppCompatActivity() {
private val TAG: String = javaClass.simpleName + " "
private var stateStr: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_a)
Log.d("LiveTest", TAG + "onCreate")
stateStr = savedInstanceState?.getString("stateStr", "切換爲橫屏")
screen_switch_btn.text = if (stateStr.isNullOrEmpty()) "切換爲橫屏" else stateStr
screen_switch_btn.setOnClickListener {
/**
*ORIENTATION_PORTRAIT = 1; 豎屏
*ORIENTATION_LANDSCAPE = 2; 橫屏
*/
val screenNum = resources.configuration.orientation
if (screenNum == 1) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
stateStr = "切換爲豎屏"
} else {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
stateStr = "切換爲橫屏"
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString("stateStr", stateStr)
super.onSaveInstanceState(outState)
Log.d("LiveTest", TAG + "onSaveInstanceState")
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
Log.d("LiveTest", TAG + "onRestoreInstanceState")
}
override fun onStart() {
super.onStart()
Log.d("LiveTest", TAG + "onStart")
}
override fun onResume() {
super.onResume()
Log.d("LiveTest", TAG + "onResume")
}
override fun onPause() {
super.onPause()
Log.d("LiveTest", TAG + "onPause")
}
override fun onStop() {
super.onStop()
Log.d("LiveTest", TAG + "onStop")
}
override fun onRestart() {
super.onRestart()
Log.d("LiveTest", TAG + "onRestart")
}
override fun onDestroy() {
super.onDestroy()
Log.d("LiveTest", TAG + "onDestroy")
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
Log.d("LiveTest", TAG + "onConfigurationChanged")
}
}
首先切換橫屏如下:
再切換豎屏:
由此可見,在8.0系統,如果不設置 android:configChanges="orientation" 屬性時,橫豎屏切換都只會執行一次生命週期。並且狀態數據等保存可以在 onSaveInstanceState 中保存,在onCreate 或者 onRestoreInstanceState 可以拿到保存的數據。
二、只設置 android:configChanges="orientation" 屬性
manifest代碼如下:
<activity
android:name=".ui.activities.ActivityA"
android:configChanges="orientation" />
切換橫屏:
切換豎屏:
由此可見,當設置了 android:configChanges="orientation" 時,橫豎屏切換都只會回調 onConfigurationChanged 方法,不會重走activity生命週期。同時是否設置 keyboardHidden|screenSize 均不影響該結果。
同時用我的9.0的小米手機測試,同樣的結果。等我找到4.4的手機再來進行測試。
果然實踐出真理,作爲程序員更要多動手嘗試,好了繼續學習~