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