Onbackpress使用导航图

问题描述

我有5个片段,如下所示:

enter image description here

但是我想当我在第5个片段上时,当我按“后退”按钮时,它返回到第2个片段。因此,在使用导航图

时该怎么做

解决方法

您可以通过navigateaction中的popUpTo中的NavControlleronBackPressed()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)
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...