简体   繁体   中英

Android: How can you pre-populate the fragment backstack?

I have an app that has one Activity that loads fragments… on initial startup it loads fragment A. From A the user can navigate to fragment B; and from B navigate to fragment C. Each time a fragment is replaced I do addToBackStack. The back button navigates as one would expect, C to B to A, and if you press back again the app exits.

I'm also using a Dropbox datastore to save all my app's data so I can move seamlessly between devices and have all my data synced. This seems to be working well. As part of my data I store which fragment was last displayed. Now when my app starts on a second device it correctly displays the most recently opened fragment. This works fine, however, I no longer have a backstack. For example, if the app is showing fragment C device one and then I start the app on device two, as expected fragment C is shown on device two. But when I press the back button, the app exits instead of showing fragment B. (Which makes sense since on device two the app only loaded fragment C.)

So my question: How do I pre-populate my baskstack such that when pressing the back button on device two that it navigates to fragment B?

I solved this by just committing multiple fragment transactions. Works for me

supportFragmentManager.beginTransaction().replace(R.id.content, Fragment1(), "f1").addToBackStack(null).commit()
supportFragmentManager.beginTransaction().replace(R.id.content, Fragment2(), "f2").addToBackStack(null).commit()
supportFragmentManager.beginTransaction().replace(R.id.content, Fragment3(), "f3").addToBackStack(null).commit()
supportFragmentManager.beginTransaction().replace(R.id.content, Fragment4(), "f4").commit()

However, for a cleaner and better solution you could also have a look at the Jetpack Navigation UI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM