如何使用接口将数据从碎片传递到回收器视图



我知道我可以轻松地将数据从RecyclerView传递到fragment,但我想做其他方式。我想从片段中触发interface,并在ViewHolder中为RecyclerView实现interface。这是我的interfaceViewHolder

interface ExampleListener{
fun onListen()
}

ViewHolder:

inner class ViewHolder(val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root), ExampleListener {
...
override fun onListen() {
// Do something
}
...
}

我不知道如何从fragment触发interface。我知道,如果我试图将数据传递给activity,我会像这样触发interface:

override fun onAttach(context: Context) {
super.onAttach(context)
if (context is ExampleListener) {
exampleListener = context
} else {
throw RuntimeException(requireContext().toString() + "must implement ExampleListener")
}
}

一种方法是更新接口,使函数接受回调

interface ExampleListener{
fun startDownloadAndListen(onComplete: () -> Unit)
}

现在在适配器中,当你开始下载按钮点击时,只需传递这个回调,它将在下载完成时被调用

button.setOnClickListener {
button.visibility = View.GONE
// Show progress bar
listener.startDownloadAndListen { 
// hide progress bar etc.
button.visibility = View.VISIBLE
}
}

最终实现ExampleListener在您的活动

override fun startDownloadAndListen(onComplete: () -> Unit) {
lifecycleScope.launch {
val result = viewModel.startDownload()   // Start and wait 
// Once result is available then call the onComplete
withContext(Dispatchers.Main) { onComplete() }
}
}

最新更新