使用数据绑定更新对象类型LiveData [英] Update Object type LiveData with Databinding

查看:226
本文介绍了使用数据绑定更新对象类型LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过与livedata的数据绑定来更新视图.让我们来看看这种情况.

I want to update views via databinding with livedata. Lets have a look at the scenario.

数据类

data class Movie(var name: String = "", var createdAt: String = "")

ViewModel

class MyViewModel: ViewModel(){
   var pageTitle: MutableLiveData<String>()
   var movie: MutableLiveData<Movie>()

   fun changeTitleAndMovieName()
       pageTitle.value = "Title Changed"
       movie.value.name = "Movie Name Changed"
   } 
}

XML

<layout>
    ...
    <TextView
        ...
        android:text="@{`Title: `+viewmodel.pageTitle `Name: `+viewmodel.movie.name}"/>

    <Button
        ...
        android:onClick="@{() -> viewmodel.changeTitleAndMovieName()}"/>

</layout>

我想做什么?

  • 按下按钮时,电影的标题和名称应更改并反映到视图中.

现在发生了什么事?

  • 由于字符串类型LiveData,仅页面标题正在更改.
  • 由于电影类型LiveData,电影名称未反映在视图中,并且我正在更改电影类型LiveData的属性.

在更改Movie的任何属性时,是否有任何方法可将Live类型的LiveData更新到视图.

Is there any way to update Movie type LiveData to the view when any property is changed of the Movie.

我不想将对象重新分配给实时数据,例如viewmodel.movie.value = Movie(...)

I dont want to re-assign the object to the livedata e.g. viewmodel.movie.value = Movie(...)

推荐答案

我已经回答了我的问题.来自此处

I have got the answer of my question. A hint from Here

参考链接的答案是待办事项变长.我有一个非常简单的解决方案.

The reference link's answer is a bit long change todo. I have got a very simple solution.

这是我所做的:

只需使用 BaseObservable 继承您的数据类,然后在对象的属性从任何地方更改后,只需调用notifyChange()方法即可.

Just inherit you Data Class with BaseObservable and just call the method notifyChange() after your Object's property change from anywhere.

数据类

  data class Movie(var name: String = "", var createdAt: String = "") : BaseObservable()

ViewModel

class MyViewModel: ViewModel(){
   var pageTitle: MutableLiveData<String>()
   var movie: MutableLiveData<Movie>()

   fun changeTitleAndMovieName()
       pageTitle.value = "Title Changed"
       movie.value.name = "Movie Name Changed"

       //here is the megic
       movie.value.notifyChange()
   } 
}

这篇关于使用数据绑定更新对象类型LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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