我有5个片段如下:
但是我想当我在第 5 个片段上时,当我按下返回按钮时,它会返回到第 2 个片段。那么我在使用导航图时该怎么做
有一种简单的方法可以通过navigate
with action
from popUpTo
inNavController
而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
。
您可以在这里查看以获取更多信息
一种简单的方法是像这样编写后退按钮。
// 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)
}