带有数据绑定的onClick ViewModel不起作用 [英] onClick with dataBinding an ViewModel doesn't work

查看:73
本文介绍了带有数据绑定的onClick ViewModel不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个项目,并使用 databinding navigation 实现MVVM模型.我的按钮位于 fragment 上,该片段以 drawer菜单项打开,问题是当我单击按钮时它什么也没做,调试器没有进入导航方法,我真的不知道我做错了什么,有人可以帮忙吗?

Im working on a project and implementing the MVVM model with databinding and navigation. My button is on a fragment that opens with a drawer menu item, the thing is when i click on the button it does nothing, the debugger doesn't go into the navigate method, I really don't know what I did wrong, can someone help?

MYACCOUNT类别:

class MyAccountFragment : BaseFragment() {

    private val vm: MyAccountViewModel by viewModel()


    override fun getViewModel(): BaseViewModel = vm

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = FragmentMyAccountBinding.inflate(inflater, container, false)
        context ?: return binding.root
        injectFeature()

        setToolbar(binding)
        subscribeUi(binding)

        return binding.root
    }

    /**
     * set toolbar
     * **/
    private fun setToolbar(binding: FragmentMyAccountBinding) {

        binding.appBarLayout.backClickListener = (activity as MainActivity).createOnBackClickListener()
    }

    /**
     * set ui
     * **/
    private fun subscribeUi(binding: FragmentMyAccountBinding) {
        binding.viewModel = vm
    }


}

MYACCVIEWMODEL

MYACCVIEWMODEL


class MyAccountViewModel constructor() : BaseViewModel() {

    fun onAddRoomClick()
    {
        navigate(MyAccountFragmentDirections.actionMyAccountFragmentToAddRoomFragment())
    }
}

在xml中,我实现了

android:onClick="@{() -> viewModel.onAddRoomClick()}"

我对所有我的 Fragments ViewModels 使用此模式,而且我真的不知道为什么它什么都不做,因此vm会初始化.在另一个 drawermenu片段上,我还有onClick方法,它可以导航到另一个片段.因此,如果有人知道该解决方案会有所帮助,请提前谢谢.

Im using this pattern for all my Fragments and ViewModels, and i really dont know why it doesn't do anything, the vm initializes. On the other drawermenu fragment I also have the onClick method and it navigates to the other fragment. So if anyone knows the solution that would be helpful, thank you in advance.

推荐答案

答案是在viewModel的初始化中.

the answer was in the initialization of the viewModel.

xml中的onClick方法位于fragment_layout中包含的content_layout中,而不是binding.viewModel = vm,我不得不做binding.content_layout.viewModel = vm.

the onClick method in xml is in a content_layout that is included in a fragment_layout and instead of binding.viewModel = vm I had to do binding.content_layout.viewModel = vm.

 private fun subscribeUi(binding: FragmentMyAccountBinding) {
        binding.contentMyAccount.viewModel = vm
    }

这篇关于带有数据绑定的onClick ViewModel不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆