【问题标题】:How to pass data from fragment to recycler view using interface如何使用接口将数据从片段传递到回收器视图
【发布时间】:2021-10-03 22:56:58
【问题描述】:

我知道我可以轻松地将数据从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")
    }
}

【问题讨论】:

  • 具体用例是什么,你想完成什么?
  • @mightyWOZ 每个 RecyclerView 项目都有一个下载按钮,用于下载某些内容(图片),当下载开始时,我想显示 ProgressBar 并隐藏按钮可见性。我无法在 ViewHolder 中用刀柄实例化 viewModel,所以我认为这是更好的方法。

标签: android kotlin android-recyclerview interface


【解决方案1】:

一种更新界面的方法,以便函数接受回调

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
     }
 }

最后在你的Activity中实现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() }
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2020-06-10
    • 2016-09-04
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多