使用数据绑定和MVVM处理onClick事件 [英] Handle onClick event with Databinding and MVVM

查看:1106
本文介绍了使用数据绑定和MVVM处理onClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Databinding ImageView 上设置 onClickListener $ c>并从 ViewModel(MVVM)控制它。

I want to set an onClickListener on an ImageView using Databinding and control it from ViewModel(MVVM).

在xml布局中,我所做的所有事情使用数据绑定实现。但是onClick事件无法正常工作。

In the xml layout all things that I've implemented with Databinding works. But onClick event is not working.

我收到此错误:


错误:找不到符号

error:cannot find symbol

XML:

<data>
    <variable
        name="photo"
        type="learn.app.papewall.model.Photo" />
    <variable
        name="viewModelDetail"
        type="learn.app.papewall.view.detail.DetailViewModel" />
</data>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.detail.DetailFragment">

    <ImageView android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
        android:scaleType="center"
        android:onClick="@{viewModelDetail.save()}"
        app:imageUrl="@{photo.urls.regular}"/>
    <TextView
        android:id="@+id/detailUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/padding_large"
        android:textColor="#000"
        android:layout_alignBottom="@+id/image"
        android:text="@{photo.user.name}"/>
</RelativeLayout>

ViewModel

fun save(photo: Photo){
    setWallpaper(photo, false)
}

片段:

viewModel.save(photoObj!!)

我不知道这是什么错误。我尝试了stackoverflow的解决方案,但没有一个解决了我的问题。

I don't know what is this error. I tried solutions from stackoverflow but none of them solved my problem.

我想使用 Databinding 设置 onClick 侦听器,然后 MVVM 任何解决方案将不胜感激,我不知道这是什么问题。

I want to set onClick Listener using Databinding and MVVM any solutions would be appreciate I don't know what is the problem.

推荐答案

您还可以尝试如下修改onClickListener:
android:onClick = @ {()-> viewModelDetail.save(photo)}

You could also try modifying your onClickListener as follows: android:onClick="@{() -> viewModelDetail.save(photo)}"

这篇关于使用数据绑定和MVVM处理onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆