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
    }