Why not work back button with android navigation component

痴心易碎 提交于 2021-01-20 12:34:35

问题


this my Auth Activity

class AuthActivity : AppCompatActivity() {
    private lateinit var navController: NavController
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityAuthBinding.inflate(layoutInflater)
        setContentView(binding.root)

        navController = Navigation.findNavController(this, fragment.id)
        NavigationUI.setupActionBarWithNavController(this, navController)

    }

    override fun onSupportNavigateUp(): Boolean {
        return NavigationUI.navigateUp(navController, null)
    }

}

LoginFragment -> if login is success goto "AcceptCodeFragment"

 viewModel.loginResponse.observe(viewLifecycleOwner, { response ->
            viewBinding.pbLogin.visible(response is Resource.Loading)
            when (response) {
                is Resource.Success -> {
                    viewBinding.tvResponse.text = response.value.message
                    val action = LoginFragmentDirections.actionLoginFragmentToAcceptCodeFragment()
                    findNavController().navigate(action)
                }
                is Resource.Error -> if (response.isNetworkError) {
                    requireView().snackBar("Check your connection")
                } else {
                    requireView().snackBar(response.errorBody.toString())
                }
            }

in AcceptCodeFragment Back button not work.

Two fragments using same viewmodel.


回答1:


Your issue is not with the back button not working, it is that LiveData is for state, not events like your loginResponse. As LiveData is for events, it redelivers the previous response when you go back to your LoginFragment. This then triggers your navigate() call again, pushing you right back to your AcceptCodeFragment.

As per the LiveData with SnackBar, Navigation, and other events blog post, LiveData cannot be directly used for events. Instead, you should consider using an event wrapper or another solution (such as a Kotlin Flow) that allow your events to only be handled once.



来源:https://stackoverflow.com/questions/64250200/why-not-work-back-button-with-android-navigation-component

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