[英]Why not work back button with android navigation component
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" LoginFragment -> 如果登录成功转到“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.在 AcceptCodeFragment 后退按钮不起作用。
Two fragments using same viewmodel.使用相同视图模型的两个片段。
Your issue is not with the back button not working, it is that LiveData
is for state , not events like your loginResponse
.您的问题不在于后退按钮不起作用,而是
LiveData
用于state ,而不是诸如loginResponse
类的loginResponse
。 As LiveData
is for events, it redelivers the previous response
when you go back to your LoginFragment
.由于
LiveData
用于事件,因此当您返回LoginFragment
时,它会重新传递先前的response
。 This then triggers your navigate()
call again, pushing you right back to your AcceptCodeFragment
.然后再次触发您的
navigate()
调用,将您推回到AcceptCodeFragment
。
As per the LiveData with SnackBar, Navigation, and other events blog post , LiveData
cannot be directly used for events.根据LiveData with SnackBar、Navigation 和其他事件博客文章,
LiveData
不能直接用于事件。 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.相反,您应该考虑使用事件包装器或其他解决方案(例如 Kotlin
Flow
),以便您的事件仅被处理一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.