【问题标题】:Android data binding inject ViewModel in custom viewAndroid数据绑定在自定义视图中注入ViewModel
【发布时间】:2018-10-13 02:55:03
【问题描述】:

我将关闭这个 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


    【解决方案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)
    }
    

    【讨论】:

      【解决方案2】:

      缺少的部分是设置Lifecycle Owner

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

      【讨论】:

      • 谢谢拉斐尔,这成功了!我正在使用以下代码val activity: AppCompatActivity = (context as ContextThemeWrapper).baseContext as AppCompatActivitybinding.setLifecycleOwner(activity) 进行活动
      • 如何支持双向数据绑定?
      猜你喜欢
      • 2016-06-05
      • 2016-04-20
      • 1970-01-01
      • 2018-09-07
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多