Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent previous fragment to show up after pressing back button using navigation controller?

I am trying to use the navigation controller right now. I want to move from LoginFragment to HomeFragment. In LoginFragment I use this code below to move to HomeFragment.

Navigation.findNavController(view).navigate(homeDestination)

However, when I tap the back button in the HomeFragment, it will go back to LoginFragment, I expect that when I tap the button it will close the app.

In old way, if I use activity instead of using Fragment, I usually do something like this to get that expected behaviour:

val intent = Intent(this,HomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)

By using those flags, I use to get the expected behavior. But I don't how to implement the same behavior using the navigation controller.

like image 378
Alexa289 Avatar asked Feb 28 '19 05:02

Alexa289


People also ask

How can we prevent back in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }

Which method is called when back button is pressed in fragment?

3. It is very important to first understand how onBackPressed() works by default for fragments... The answer is short: it first searches for any added fragment via addToBackStack, if there is one, it does exactly the same as popBackStack() to pop it, otherwise it does the default onBackPressed() for the activity.


2 Answers

Navigation offers a popUpTo and popUpToInclusive attributes for removing fragments from the back stack as part of a navigate() operation.

This can be set either in XML:

<!-- Add to your Navigation XML, then use navigate(R.id.go_home) -->
<action
  android:id="@+id/go_home"
  app:destination="@+id/home_fragment"
  app:popUpTo="@+id/destination_to_pop"
  app:popUpToInclusive="true"/>

Or set it programmatically:

NavOptions navOptions = new NavOptions.Builder()
    .setPopUpTo(R.id.destination_to_pop, true)
    .build();
Navigation.findNavController(view).navigate(homeDestination, navOptions)

You can also use the id of a <navigation> element as well.

like image 116
ianhanniballake Avatar answered Oct 11 '22 16:10

ianhanniballake


I was following the answer of Ian but I had been having bad luck since I didn't know what the popUpTo would be.

So we have to use the id Of nav Graph there.

app:popUpTo="@+id/idOfNavGraph". //id of nav graph

<action
  android:id="@+id/go_home"
  app:destination="@+id/home_fragment"
  app:popUpTo="@+id/idOfNavGraph". //id of nav graph
  app:popUpToInclusive="true"/>
like image 21
erluxman Avatar answered Oct 11 '22 17:10

erluxman