【发布时间】: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