问题描述
我有5个片段,如下所示:
但是我想当我在第5个片段上时,当我按“后退”按钮时,它返回到第2个片段。因此,在使用导航图
时该怎么做解决方法
您可以通过navigate
中action
中的popUpTo
中的NavController
和onBackPressed()
来super.onBackPressed()
来完成此操作。
示例:
<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)
...
}
您可能还希望添加app:popUpToInclusive
。
您可以检查here以获得更多信息
,一种简单的方法是这样对后退按钮进行编码。
// 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)
}