首页 > 解决方案 > 安卓数据绑定。按钮 onClick 不起作用

问题描述

我卡在这里了,求助。

我有以下代码:

简介片段:

    @AndroidEntryPoint
    class ProfileFragment : Fragment() {
        private val profileViewModel: ProfileViewModel by viewModels()
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            val binding = FragmentProfileBinding.inflate(inflater, container, false)
            binding.viewModel = profileViewModel
            binding.lifecycleOwner = viewLifecycleOwner
    
            return binding.root
        }
    }

配置文件视图模型:

class ProfileViewModel @ViewModelInject constructor(
    @ApplicationContext private val context: Context,
    private val profileRepository: ProfileRepository
) : ViewModel() {

   fun getUser() {
     ....
   } 
}

片段配置文件.xml:

 <data>

    <variable
        name="viewModel"
        type="my.app.viewmodel.ProfileViewModel" />

</data>

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:onClick="@{()->viewModel.getUser()}" />

</LinearLayout>

问题是,onClick无论我做什么以及如何尝试,都不会触发。但是,只要我这样做,ProfileFragment它就可以正常工作:

binding.myButton.setOnClickListener {
   profileViewModel.getUser()
}

有任何想法吗?因为我被困在这里

标签: androidkotlinandroid-databindingandroid-architecture-components

解决方案


我不确定这个问题是否仍然存在,但如果您使用数据绑定和 hilt 进行依赖注入,请在您的片段 onViewCreated 中添加以下行

binding.lifecycleOwner = this
binding.viewModel = profileViewModel

推荐阅读