为什么不使用Android导航组件返回按钮 [英] Why not work back button with android navigation component
问题描述
这是我的身份验证活动
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->如果登录成功,则转到"AcceptCodeFragment"
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())
}
}
AcceptCodeFragment后退按钮中的
不起作用.
in AcceptCodeFragment Back button not work.
使用相同的视图模型的两个片段.
Two fragments using same viewmodel.
推荐答案
您的问题不在于后退按钮不起作用,这是因为LiveData
用于状态,而不是像您的loginResponse
.由于LiveData
用于事件,因此当您返回LoginFragment
时,它将重新提供以前的response
.然后,这会再次触发您的navigate()
通话,将您向右推回到AcceptCodeFragment
.
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
.
按照带有SnackBar,导航和其他事件博客文章的LiveData ,LiveData
不能直接用于事件.相反,您应该考虑使用事件包装器或其他解决方案(例如Kotlin Flow
),该解决方案只能将事件处理一次.
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.
这篇关于为什么不使用Android导航组件返回按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!