Navigation Architecture Component - Login screen

坚强是说给别人听的谎言 提交于 2019-11-28 11:39:12

One of the solutions that i can propose is to override inside your activity onBackPressed method, and finish the activity if your current destination(before on back pressed handled) is login fragment.

override fun onBackPressed() {
    val currentDestination=NavHostFragment.findNavController(nav_host_fragment).currentDestination
    when(currentDestination.id) {
        R.id.loginFragment -> {
            finish()
        }
    }
    super.onBackPressed()
}

IMHO how I do it in my app is a little cleaner. Just add these settings in the nav graph:

<fragment
    android:id="@+id/profile_dest"
    android:name="com.example.ProfileFragment">
    <action
        android:id="@+id/action_profile_dest_to_login_dest"
        app:destination="@id/login_dest"
        app:popUpTo="@+id/profile_dest"
        app:popUpToInclusive="true" />       
</fragment>

and then navigate to login via

findNavController().navigate(R.id.action_profile_dest_to_login_dest).

popUpTo and popUpToInclusive close ProfileFragment when we navigate to LoginFragment so if the user navigates back, it exits the app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!