Navigation Architecture Component - Login screen

冷暖自知 提交于 2019-11-27 02:56:21

问题


I am planning to implement navigation like this:


The problem I face is when user is in LoginFragmennt and presses back button it again loads up LognFragment ie. stuck in loop.

I navigate to LoginnFragment using conditional navigation as per this answer.

How to properly implement this?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/51582674/navigation-architecture-component-login-screen

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