旋转屏幕,多次调用活动的生命周期



我有一个具有地图片段的活动应用程序。

当活动开始时,将调用以下活动生命周期

onCreate
onStart
onResume

但是当我旋转设备时,将调用以下生命周期!

onPause
onStop
onDestroy
onCreate
onCreate
onStart
onStart
onResume
onResume

当我再次旋转它时,

onPause
onPause
onStop
onStop
onDestroy
onDestroy
onCreate
onCreate
onCreate
onStart
onStart
onStart
onResume
onResume
onResume

我的代码如下

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMapBinding = DataBindingUtil.setContentView(this, R.layout.activity_maps)
mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
val mapFragment =
supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
observeErrorResponse()
Log.d("MainActivity","onCreate")
}

override fun onStart() {
super.onStart()
mainViewModel.syncStart()
Log.d("MainActivity","onStart")
}
override fun onStop() {
super.onStop()
mainViewModel.syncStop()
Log.d("MainActivity","onStop")
}
override fun onPause() {
super.onPause()
Log.d("MainActivity","onPause")
}
override fun onResume() {
super.onResume()
Log.d("MainActivity","onResume")
}
override fun onDestroy() {
super.onDestroy()
Log.d("MainActivity","onDestroy")
}
override fun onRestart() {
super.onRestart()
Log.d("MainActivity","onRestart")
}

我不熟悉 kotlin,但在 java(我使用(中,我会检查片段管理器中是否已添加片段,如果已经添加,请不要添加另一个,因为当配置状态更改(在您的情况下为屏幕旋转(时,android 会破坏活动并重新创建它。因此,将再次调用活动的生命周期方法

发生这种情况时,您必须"保存"/"存储"数据。在override fun onCreate(savedInstanceState: Bundle?)之前实现这一点:

override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outstate.<type in put in android studio and select the one you need in the dropdown options(such as putParceleable, putString, putInt etc.)>(<Create a const val variable in a separate kotlin file and put the name of the variable here(it will act as the key), android studio will automatically import it>, <here you need to put the variable that contains the data that is being removed/gone when you rotate the device>)
}

然后在override fun onCreate(savedInstanceState: Bundle?)之后实现:

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if (savedInstanceState != null){
<name of the variable you put in the outstate> = savedInstanceState.<type in get and select the one you need(it must be the same as the one in the put, ex. if you have put putString, provide getString here.)>(<name of the key you implemented in the outstate>)
}
}

最新更新