background
Over the weekend, a student left a message to me in the background of wechat public account, saying that he had read two articles I wrote before and did you understand the official component of Google Navigation? Do you know how to use Google Navigation? Later, I also tried to use Navigation, but encountered a problem: every time I entered the next Fragment, a new instance would be created and not reused, regardless of whether there was an instance of the Fragment in the task stack. To illustrate, I recorded a GIF
The problem is that our previous OneFragment saved some state or data, and when we jump to OneFragment, the state or data we saved before will disappear because of creating a new instance.
popUpTo/popUpToInclusive
Set two properties in the action
app:popUpTo="@id/oneFragment"
app:popUpToInclusive="true"
Copy the code
We can achieve the following effect:
If we are using The Kotlin language, then we need to change the local libraries that we refer to in Gradle
implementation "android.arch.navigation:navigation-fragment-ktx:$nav_version" // use -ktx for Kotlin
implementation "android.arch.navigation:navigation-ui-ktx:$nav_version" // use -ktx for Kotlin
Copy the code
2. Call the Fragment method:
findNavController().navigate(R.id.action_oneFragment_to_twoFragment)
Copy the code
Note that the findNavController package referenced here is:
import androidx.navigation.fragment.findNavController
Copy the code
3. Those of you who have seen my previous code may have noticed that I went out of my way to emphasize this
findNavController().navigate(R.id.action_oneFragment_to_twoFragment)
Copy the code
This id is best used with the action ID, which can be used with the animation in the action or with the popUpTo popUpToInclusive property in the action. Before, a student left me a message on the public account asking why popUpTo/popUpToInclusive did not work after the Demo. The problem is that the action Id code should be updated. Welcome star and download. If you have any questions, please leave a message to me!
The question remains….
It looks like, when we’re retracting, it’s normal. However, we still have the problem that every time we click, we still create a new Fragment, a new instance, but when we create the new instance, we remove the previous one. I’ll show you how to solve this problem in my next article!