How to update custom view data to data binding?

Viewed 550

I'm trying to update custom view data to data binding (Jetpack). The custom view has attributes so I was making ViewBindingAdapter. But, That's update only one time on Activity onCreate or init ViewModel. I wanna update custom view data anytime.

Custom View

var title: String
    get() {
        return tv_customView_title.text.toString()
    }
    set(value) {
        tv_customView_title.text = value
    }

var content: String
    get() {
        return tv_customView_content.text.toString()
    }
    set(value) {
        tv_customView_content.text = value
    }

Layout XML

<CustomView
    android:id="@+id/customView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    app:rideInfo_title="@{viewModel.title}"
    app:rideInfo_content="@{viewModel.content}"
    app:layout_constraintTop_toTopOf="parent"/>

ViewBindingAdapter

@JvmStatic
@BindingAdapter("app:customView_title")
fun setCustomViewTitle(view: CustomView, title: String?) {
    view.title = title.toString()
}

@JvmStatic
@BindingAdapter("app:customView_content")
fun setCustomViewContent(view: CustomView, content: String?) {
    view.content = content.toString()
}

ViewModel

var title = MutableLiveData("Title")
var content = MutableLiveData("Content")

I'm using the custom view update on Activity to observe Because That can't update LiveData Value <-> CustomView anytime... But I think there will be a better solution.

viewModel.title.observe(this, { customView.title = it })
viewModel.content.observe(this, { customView.content = it })

Please help me.

English is very very hard

1 Answers

I have noticed that you are using vars for title and content live datas inside your ViewModel.

If you are reassigning the variable itself (e.g. content = MutableLiveData("New Content")) when updating the values that's what causing the issue.

You should be using setValue or Kotlin extension property MutableLiveData#value when updating your state (e.g. content.value = "New Content").

Also you should use non-reassignable vals for mutable live data.

Related