简体   繁体   English

在 RecyclerView Adapter 中使用 ViewModel 的实时数据

[英]Using ViewModel's live data in a RecyclerView Adapter

Recently had a circumstance where I had constantly observe the clicked view in a ViewHolder attached to a RecyclerView.最近有一种情况,我一直在观察附加到 RecyclerView 的 ViewHolder 中的单击视图。 I have tried setting onclick listener and for my bad it doesn't work out.我曾尝试设置 onclick 侦听器,但对我而言,它不起作用。 Later something worked for me was passing a livedata to the adapter and posting the value to the livedata when click event is made on the view.后来对我有用的是将实时数据传递给适配器,并在视图上发生单击事件时将值发布到实时数据。 It is as below.,如下,

// live data
val selectedItem: MutableLiveData<String> by lazy { MutableLiveData<String>() }

// passing to adapter
binding.myRecycler.adapter = myAdapter(elements, myViewModel.selectedItem)

// adapter
class myAdapter(
    private val elements: List<Element>,
    private val selectedItem: MutableLiveData<String>,
) : RecyclerView.Adapter<myViewHolder>() {

    override fun onBindViewHolder(holder: myViewHolder, position: Int) {
        val element = elements[position]
        holder.card.setOnClickListener {
            selectedItem.postValue(element.uid)
        }
    }
}

I havent seen anyone recommending this way on most question about this in stackoverflow.我还没有看到有人在 stackoverflow 中对大多数有关此的问题推荐这种方式。

what are the drawbacks of passing live data to recyclerview adapter?将实时数据传递给 recyclerview 适配器有什么缺点? when I observe the changes, it is working exactly the way I want.当我观察这些变化时,它完全按照我想要的方式工作。 If this is not the correct way, what is the correct way to solve this?如果这不是正确的方法,那么解决这个问题的正确方法是什么?

My intention is to store the uid s of the clicked views in the adapter to a database,.我的目的是将适配器中单击视图的uid存储到数据库中。

I think it`s not good idea for use viewModel and liveData to click event in android.我认为在 android 中使用 viewModel 和 liveData 单击事件不是一个好主意。
because use more observer in app not good.因为在应用程序中使用更多的观察者不好。
the viewModel in android designed for work with activity and fragment and it use them lifecycle. android 中的 viewModel 设计用于处理活动和片段,并使用它们的生命周期。 click event is main thread process but post in live data is use for background calls.单击事件是主线程进程,但实时数据中的发布用于后台调用。

the easiest way is use callback .最简单的方法是使用回调
but if you use kotlin for developing android app you can use higher order function .但是如果您使用 kotlin 开发 android 应用程序,您可以使用高阶函数

i hope the answer is true and help you我希望答案是真实的并能帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM