从 xml 调用视图模型方法不调用 android 中的问题

Call View Model method from xml not invoke Issue in android

    **The XMl file where from calling method of view Model**
    <variable
        name="viewModelDetail"
        type="com.joyor.viewmodel.HomeViewModel" />
</data>
        <ImageView
            android:id="@+id/profile"
            android:layout_width="@dimen/_30sdp"
            android:layout_height="match_parent"
            android:layout_marginEnd="@dimen/_5sdp"
            android:onClick="@{viewModelDetail.onProfileClick}"
            android:padding="@dimen/_5sdp"
            android:src="@drawable/ic_profile"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
         ....
         ......
         .......

查看模型Class实现,点击调用方法

 class HomeViewModel : ViewModel() {
    
        var isProfileClick: MutableLiveData<Boolean> = MutableLiveData()
    
       fun onProfileClick(view:View) {
            isProfileClick.value = true
        }
    
    }

如何在 MVVM 中点击调用 imageView 的方法来调用 viewModel 方法

对您的 onClick 属性进行此更改

android:onClick="@{() -> viewModelDetail.onProfileClick}"

同样在您的 Activity/Fragment class 中确保您正在设置 ViewModel 属性 并调用执行挂起的绑定,如下所示。

binding.viewModel = viewModel
binding.lifecycleOwner = this
binding.executePendingBindings()