Middle
How to add a fragment synchronously or asynchronously?
sobes.tech AI
Answer from AI
To add a fragment synchronously, use commit(). The fragment manager's transaction is executed immediately.
To add a fragment asynchronously, use commitAllowingStateLoss(). This may lead to loss of state if the activity is destroyed before the transaction is committed. Alternatively, you can use commit() combined with executePendingTransactions() to execute the transaction immediately after calling commit().
// Synchronous addition
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, yourFragment)
.commit()
// Asynchronous addition (with potential for state loss)
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, yourFragment)
.commitAllowingStateLoss()
// Asynchronous addition with immediate execution
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, yourFragment)
.commit()
supportFragmentManager.executePendingTransactions()