簡體   English   中英

Android數據綁定在自定義視圖中注入ViewModel

[英]Android data binding inject ViewModel in custom view

我將關閉此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的值更新

缺少的部分是設置生命周期所有者

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

回答幫助了我,並希望拋出一個可以添加的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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM