0

I have 5 fragment as follows:

enter image description here

But I want when I am on 5th fragment, when I press back button it returns to 2nd fragment. So how do I do it while I use navigation graph

Thang
  • 409
  • 1
  • 6
  • 17
  • Are you saying that when you go from 4 to 5, it currently goes back to 4 and you want to change that to going back to 2? Or that it currently goes back to 2 and you want to instead have it go back to 4? Can you include your navigation graph and how to go from 4 to 5? – ianhanniballake Sep 09 '20 at 02:00

2 Answers2

0

There is a simply way you can do that by navigate the action with popUpTo from NavController in onBackPressed() instead of super.onBackPressed().

example:

<action android:id="@+id/action_5_to_2"
      app:popUpTo="@id/destination_2" />
override fun onBackPressed(){
    ...
    findNavController(view).navigate(R.id.action_5_to_2)
    ...
}

And you may want to add app:popUpToInclusive as also.

You can check here to get further information

Hababa
  • 551
  • 5
  • 8
0

An easy way is to code your back button like this.

    // Your back button
    onBackPressButton.setOnClickListener {

    // intent says that this @FifthFragment/CurrentActivity is going to do something with @SecondFragment/@NextActivity
    val intent = Intent(this@FifthFragment, SecondFragment::class.java)

    // The intent.flags tells to clear the @FifthFragment/@CurrentActivity and start @SecondFragment/@NextActiviy
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)

    // startActivity starts your intent 
    startActivity(intent)
    }

Branddd
  • 78
  • 12