Android数据绑定在自定义视图中注入ViewModel

问题描述 投票:2回答:2

我将关闭此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)
    }
}

一切正常,对profileManager.profile()的API调用是成功的,使用正确的设置成功创建了ViewProfileBinding类。问题是,当我执行name.postValue(profile.name)时,视图未使用profile.name的值更新

android data-binding kotlin android-custom-view android-viewmodel
2个回答
2
投票

缺少的是设置一个Lifecycle Owner

binding.setLifecycleOwner(parent) //parent should be a fragment or an activity

1
投票

答案帮助了我,并希望抛出一个可以添加的util方法来获取LifeCycleOwner

fun getLifeCycleOwner(view: View): LifecycleOwner? {
    var context = view.context

    while (context is ContextWrapper) {
        if (context is LifecycleOwner) {
            return context
        }
        context = context.baseContext
    }

    return null
}

在你看来:

getLifeCycleOwner(this)?.let{
   binding.setLifecycleOwner(it)
}
© www.soinside.com 2019 - 2024. All rights reserved.