我是Android Jetpack导航架构的新手.我正在一个新应用上试用.有一个活动和几个片段,其中两个是登录屏幕和邮箱登录屏幕.我在导航XML中定义了这些片段.该应用程序的流程如下所示:

Login screenEmail Login screen

What I want is, after navigating to the email login screen, when I press back, the app exits. Meaning the back-stack for login screen is removed. I know login screens aren't supposed to work that way, but I'm still just figuring things out.

I followed the documentation from Google's Get started with the Navigation component. It said, using app:popUpTo and app:popUpToInclusive="true" is supposed to clear the backstack, yet when I press back on email login screen, it still goes back to login instead of exiting.

所以,我已经试过了.

nav_main.xml

<fragment android:id="@+id/loginFragment"
          android:name="com.example.myapp.ui.main.LoginFragment"
          android:label="@string/login"
          tools:layout="@layout/fragment_login" >
    
    <action
        android:id="@+id/action_login_to_emailLoginFragment"
        app:destination="@id/emailLoginFragment"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/slide_out_right"
        app:popUpTo="@+id/emailLoginFragment"
        app:popUpToInclusive="true"/>

</fragment>

<fragment android:id="@+id/emailLoginFragment"
          android:name="com.example.myapp.ui.main.EmailLoginFragment"
          android:label="EmailLoginFragment"
          tools:layout="@layout/fragment_login_email" />

LoginFragment.kt

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    binding.emailLoginButton.setOnClickListener {
        findNavController().navigate(R.id.action_login_to_emailLoginFragment)
    }
    
    return binding.root
}

我给了一个按钮一个点击事件.在其中,我使用导航控制器导航到邮箱登录屏幕,给它一个操作ID.在<action>中,有app:popUpToapp:popUpToInclusive="true".

在一遍又一遍地阅读文档,以及大量的StackOverflow问题之后,我发现这些属性应该会将我的登录屏幕从后堆栈中移除.但他们没有.按钮确实会导航到邮箱登录屏幕,但当我按back时,它仍然会返回到登录屏幕,而不是退出应用程序.我错过了什么?

推荐答案

<action
        android:id="@+id/action_login_to_emailLoginFragment"
        app:destination="@id/emailLoginFragment"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/slide_out_right"
        app:popUpTo="@+id/loginFragment"
        app:popUpToInclusive="true"/>

你的弹出窗口将返回到邮箱登录,然后由于包含内容而弹出.

Kotlin相关问答推荐

将Kotlin中的函数变量委托给通用类

等待下一个值时暂停Kotlin Coroutine

Kotlin接口方法默认值&;可传递依赖项

限制通用Kotlin枚举为特定类型

为什么我们在 kotlin 中需要 noinline?

多次运行espresso测试

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

什么是 .kotlin_builtins 文件,我可以从我的 uberjars 中省略它们吗?

调用单元测试验证伴随对象方法

requireNotNull vs sure !! 操作符

如何将vararg转换为list?

封闭 lambda 的隐式参数被shadowed

如何为kotlin异常生成SerialVersionId?

重复构建失败To use Coroutine features, you must add `ktx`......

Kotlin协程无法处理异常

Kotlin out-projected 类型禁止使用

Kotlin - 如何获取注释属性值

具有多个 parameter的 Kotlin 枚举

为什么在 Kotlin 中return可以返回一个return?