Update Object type LiveData with Databinding

…衆ロ難τιáo~ 提交于 2019-12-13 03:39:50

问题


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

Data Class

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>

What I want to do?

  • When the button is pressed, the title and the name of movie should change and reflect to the view.

What is happening now?

  • Only page title is changing because of String type LiveData.
  • Movie name is NOT being reflected in the view because of Movie type LiveData and I am changing the property of Movie type LiveData's property.

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

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


回答1:


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.

Here's what I did:

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

i.e. Data Class

  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()
   } 
}


来源:https://stackoverflow.com/questions/56741250/update-object-type-livedata-with-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!