【问题标题】:Call View Model method from xml not invoke Issue in android从 xml 调用 View Model 方法不会在 android 中调用问题
【发布时间】:2021-05-25 20:23:03
【问题描述】:
    **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 HomeViewModel : ViewModel() {
    
        var isProfileClick: MutableLiveData<Boolean> = MutableLiveData()
    
       fun onProfileClick(view:View) {
            isProfileClick.value = true
        }
    
    }

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

【问题讨论】:

    标签: android xml kotlin mvvm viewmodel


    【解决方案1】:

    对您的 onClick 属性进行此更改

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

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

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

    【讨论】:

    • 这解决了您的问题吗?如果是,请标记此答案很有帮助,以免其他人不必要地回答。
    • 问题是来自活动/片段的 viewModel 未正确绑定 xml viewmodel 变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多