I'm struggling to stop regenerating fragment when I fold foldable phone.
This is the code generating fragment instance.
class ExampleActivity: AppCompatActivity() {
private var mapFragment: MapFragment? = null
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_example)
mapFragment = supportFragmentManager.findFragmentById(R.id.exampleFragmentId) as MapFragment?
?: MapFragment.newInstance().also {
supportFragmentManager.commit {
add(R.id.exampleFragmentId, it)
}
}
}
...
}
When I fold the phone, the activity goes to onCreate, and draw this fragment again.
Does anyone know that why this logic draw the fragment again every time when I fold the foldable phone?
Or can you guys answer me some way to solve this problem?
Android System do its best to handle the configuration change correctly.
reference
Google recommend you to save your state properly and restore in when configuration changes.
but anyway if you want to prevent recreation, fill in the manifest like below.
reference