0

我有5个片段如下:

在此处输入图像描述

但是我想当我在第 5 个片段上时,当我按下返回按钮时,它会返回到第 2 个片段。那么我在使用导航图时该怎么做

4

2 回答 2

0

有一种简单的方法可以通过navigatewith actionfrom popUpToinNavControlleronBackPressed()不是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

您可以在这里查看以获取更多信息

于 2020-09-09T02:42:10.833 回答
0

一种简单的方法是像这样编写后退按钮。

    // 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)
    }

于 2020-09-09T08:34:59.997 回答