Home > other >  Android Back Button Fragment to Fragment - State
Android Back Button Fragment to Fragment - State

Time:10-08

I'm newer to Android development, so maybe I'm missing something obvious. I have a main activity, and from there I have various fragments I am navigating between using the navigation manager. My issue, is that if the user presses the back button, effectively switching to the previous fragment in the stack, the UI data is entirely lost. I've seen solutions for this that are either outdated, or seem unnecessarily complex, which makes me think they're not correct. For example, one solution was to individually store every value for every view in the fragment, manually, and restore them on back navigation... which I assume it not proper, or else Android is very poorly engineered as a framework.

Is there a proper method for retaining a fragment state for when the user clicks the back button so that the fragment they land on has the previous state information?

I am using Kotlin by the way, though any sort of answer is fine.

CodePudding user response:

Fragment container view is properly explained with video in the official android developer website you can use it

https://developer.android.com/guide/navigation/navigation-getting-started

To pass data you can use parcelableArg which is explained here

https://developer.android.com/guide/navigation/navigation-pass-data

For back button navigation you need to use ViewPager2 which is explained here

https://developer.android.com/jetpack/androidx/releases/viewpager2

Sliding between fragment is explained here

https://developer.android.com/develop/ui/views/animations/screen-slide-2

Source code example is available here

https://github.com/android/views-widgets-samples/tree/main/ViewPager2

To save state of fragment, the code is explained here

https://developer.android.com/guide/fragments/saving-state

If you want to store Bit Data, you can use Room, explained here

https://developer.android.com/training/data-storage/room

or use second option as DataStore explained here

https://developer.android.com/topic/libraries/architecture/datastore

CodePudding user response:

I figured out the issue. The default produced Android Studio code for my fragment has the layout inflated in onCreateView. I didn't realize it, but this inflate was being called again when the fragment was brought back on back button press. Preventing the inflate from being called again keeps the UI state.

  • Related