I've got the problem with creating multiple fragment instances in OnCreate. When i close the app using Home button and I will return to the app, the fragment instance is created one more time. How can I prevent this?
fragment = FragmentMain.newInstance(intent.extras?.getSerializable(DATA_MAIN)).also {
supportFragmentManager.beginTransaction()
.add(frameLayout.id, it, FragmentMain::class.java.simpleName)
.addToBackStack(FragmentMain::class.java.simpleName)
.commit()
}
CodePudding user response:
This is expected behavior, as Android recreates the fragments after process death that are added to the fragment manager.
You're just also adding a 2nd new fragment on top of the one created by Android, which, you probably don't want to do.
fragment = when {
savedInstanceState == null -> FragmentMain.newInstance(intent.extras?.getSerializable(DATA_MAIN)).also {
supportFragmentManager.beginTransaction()
.add(frameLayout.id, it, FragmentMain::class.java.simpleName)
.addToBackStack(FragmentMain::class.java.simpleName)
.commit()
}
else -> supportFragmentManager.findFragmentByTag(FragmentMain::class.java.simpleName)
}