0

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?

1 Answers1

0

Android System do its best to handle the configuration change correctly.

  • Tear down the whole UI and restore it. You can restrict the Activity recreation when configuration changes, but it's not recommended.

In the View system, disabling Activity recreation can make it much more difficult to use alternative resources. This is because the system no longer applies them for you. In apps built with the View system, only disable Activity recreation as a last resort when you must avoid restarts due to a configuration change. It is not recommended for most applications.

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.

<activity
    android:name=".ExampleActivity"
    android:configChanges="smallestScreenSize|screenSize|screenLayout"
>

reference

Watermelon
  • 452
  • 2
  • 5
  • Thank you so much! It worked for me! I was only concentrated on Activity and Fragment's lifecycle.. Thanks a lot!! have a good day~~! – Hello World Apr 03 '23 at 14:59