我要关闭这个 stackoverflow 答案https://stackoverflow.com/a/34817565/4052264以将数据对象绑定到自定义视图。然而,在一切都设置好后,我的视图没有用数据更新,而是TextView
保持空白。这是我的代码(简化,为了适合这里)
activity_profile.xml
::
<layout xmlns...>
<data>
<variable name="viewModel" type="com.example.ProfileViewModel"/>
</data>
<com.example.MyProfileCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:viewModel="@{viewModel}">
</layout>
view_profile.xml
:
<layout xmlns...>
<data>
<variable name="viewModel" type="com.example.ProfileViewModel"/>
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{viewModel.name}">
</layout>
MyProfileCustomView.kt
:
class MyProfileCustomView : FrameLayout {
constructor...
private val binding: ViewProfileBinding = ViewProfileBinding.inflate(LayoutInflater.from(context), this, true)
fun setViewModel(profileViewModel: ProfileViewModel) {
binding.viewModel = profileViewModel
}
}
ProfileViewModel.kt
:
class ProfileViewModel(application: Application) : BaseViewModel(application) {
val name = MutableLiveData<String>()
init {
profileManager.profile()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(::onProfileSuccess, Timber::d)
}
fun onProfileSuccess(profile: Profile) {
name.postValue(profile.name)
}
}
一切正常,API 调用profileManager.profile()
成功,ViewProfileBinding
使用正确的设置成功创建了类。问题是当我这样做时name.postValue(profile.name)
,视图没有更新为profile.name