【问题标题】:Android Data Binding. Button onClick not working安卓数据绑定。按钮 onClick 不起作用
【发布时间】:2021-02-08 21:31:12
【问题描述】:

我卡在这里了,求助。

我有以下代码:

个人资料片段:

    @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
        }
    }

ProfileViewModel:

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

   fun getUser() {
     ....
   } 
}

fragment_profile.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()
}

有什么想法吗?因为我被困在这里了

【问题讨论】:

  • 我认为您的问题与此行有关:private val profileViewModel: ProfileViewModel by viewModels()。由于您已经为视图模型参数化了构造函数,因此片段无法为您保留该实例,因为您可能没有向它提供 ViewModelProvider.Factory。不确定您的潜在 DI。
  • @JeelVankhede 不幸的是,您所描述的与我的问题无关。

标签: android kotlin android-databinding android-architecture-components


【解决方案1】:

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

binding.lifecycleOwner = this
binding.viewModel = profileViewModel

【讨论】:

    【解决方案2】:

    解决这个问题的方法是在 onCreateView 中添加对自身的片段引用:

    binding.<fragment_name> = this
    

    像这样:

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            Log.v(TAG, "onCreateView")
            binding = FragmentSettingsBinding.inflate(inflater, container, false)        
            binding.settingsFragment = this  <---
            binding.lifecycleOwner = viewLifecycleOwner
            return binding.root
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 2018-12-27
      • 2019-08-09
      • 2018-05-10
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 2012-03-26
      • 2015-02-24
      相关资源
      最近更新 更多