'Android Navigation add to back stack
I tried use Android Navigation component and have a problem with back stack.
I have Fragment A, B.To navigate from A to B, I write:
Navigation.findNavController(view).navigate(R.id.a_to_b)
But how can i return back to A on back button clicked?
Solution 1:[1]
The fragment A is in your backstack, so you can just implement a click listener for your button and, for example, use this solution.
It provides an example and some explanations:
New release androidx.activity ver. 1.0.0-alpha07 brings some changes
More explanations in android official guide: Provide custom back navigation ```java public class MyFragment extends Fragment {
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // This callback will only be called when MyFragment is at least Started. OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) { @Override public void handleOnBackPressed() { // Handle the back button event } }; requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
Happy coding!
Solution 2:[2]
It's well known that the Nav library is supposed to take care of pushing and popping from the backstack itself. I've spent a couple of hours hunting a missing line though so thought this might help future googlers, from the basic sample:
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_splash_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/launch_nav_graph"
tools:context=".launch.SplashActivity" />
If you do not set the defaultNavHost, you basically need to take care of the backstack yourself. This line is crucial to automatically add fragments to the back stack.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ????? ?????? |
| Solution 2 | Daniel Wilson |
