android - 安卓数据绑定。按钮 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()
}
有任何想法吗?因为我被困在这里
解决方案
我不确定这个问题是否仍然存在,但如果您使用数据绑定和 hilt 进行依赖注入,请在您的片段 onViewCreated 中添加以下行
binding.lifecycleOwner = this
binding.viewModel = profileViewModel
推荐阅读
- reactjs - React-Redux Actions 可能没有未定义的“类型”属性
- mysql - 创建新记录时,Mysql 偏移量和限制会给出模棱两可的结果
- graph - 如何获得 Rascal 上下文无关文法的强连通分量
- google-bigquery - Unix时间到日期时间谷歌bigquery?
- c - 使用 R 编辑二进制文件
- java - 如何在 Spring Boot 中记录对未知 URL 端点的请求?
- tensorflow - Dataset.map 可以以某种方式并行化 tf.py_func 调用吗?
- dictionary - 添加大于 n 过滤器的对
- sql - 如何从 SQL 查询中仅选择第二个结果
- java - 比较器:将 2 个对象与可以为空的字段进行比较