Kotlin:如何将数据从RecyclerView适配器发送到片段 [英] Kotlin: How to send data from RecyclerView adapter to a Fragment

查看:61
本文介绍了Kotlin:如何将数据从RecyclerView适配器发送到片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android的新手,也是Kotlin的新手(来自iOS Swift开发).我有一个活动,有一个片段,该片段内是一个RecyclerView.当用户在RecyclerView中点击一行时,我想显示一个对话框并采取一些措施.

I'm new to Android and new to Kotlin (coming from iOS Swift development). I have an activity that has a fragment, inside the fragment is a RecyclerView. When the user taps on a row in the RecyclerView I want to show a dialog and take some action.

在适配器中,我具有CustomViewHolder和onClickListener.从那里,我可以捕获用户轻松点击的行.但是,如何将这些信息传递回片段,以便我可以采取行动/显示对话框?

In the adapter I have the CustomViewHolder and onClickListener. From there I can capture the row the user tapped on easily. But how do I pass this information back to the fragment so that I can take action / display a dialog?

谢谢!

推荐答案

让适配器将lambda作为参数...例如

Have your adapter take a lambda as a parameter...for example

class YourAdapter(val listener: (YourDataType) -> Unit)

在视图持有者中,当用户单击行时,您将调用该侦听器.

In your view holder you'd then invoke that listener when user clicks on row.

holder.itemView.setOnClickListener { listener(data) }

在您的片段中,您将拥有类似的东西:

In your fragment you'd have something like:

    yourAdapter = YourAdapter {
        // invoked when user clicks on row
    }

这篇关于Kotlin:如何将数据从RecyclerView适配器发送到片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆