简体   繁体   中英

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" />
         ....
         ......
         .......

View Model Class implementation where on click for invoke method

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

How to invoke method for imageView on click in MVVM to invoke viewModel method

Make this changes to your onClick attribute

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

Also in your Activity/Fragment class make sure you are setting ViewModel property and call execute pending bindings, like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM