I have 5 fragment as follows:
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
I have 5 fragment as follows:
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
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
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)
}