【问题标题】:Why not work back button with android navigation component为什么不使用 android 导航组件的后退按钮
【发布时间】:2020-10-07 18:27:42
【问题描述】:

这是我的身份验证活动

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”

 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 中的后退按钮不起作用。

使用相同视图模型的两个片段。

【问题讨论】:

    标签: android kotlin navigation-architecture


    【解决方案1】:

    您的问题不在于后退按钮不起作用,而是LiveData 用于状态,而不是像您的loginResponse 这样的事件。由于LiveData 用于事件,因此当您返回LoginFragment 时,它会重新传递之前的response。然后这会再次触发您的navigate() 呼叫,将您推回您的AcceptCodeFragment

    根据LiveData with SnackBar, Navigation, and other events blog postLiveData 不能直接用于事件。相反,您应该考虑使用事件包装器或其他解决方案(例如 Kotlin Flow),让您的事件只被处理一次。

    【讨论】:

    • 我有 5 天的时间参加黑客马拉松。所以我在尝试快速编写代码时遇到了这个问题。由于有 2 个片段容器,我的重点就在那里。当我看到你的回答时,我笑着说,哇,这一定是问题所在。这确实是问题所在。非常感谢您的回复。
    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多