如何使用数据绑定初始化 Recycler 视图适配器上的点击监听器?

How to initialise click listener on Recycler view adapter using Databinding?

我打算为所有动态布局制作一个通用适配器,通常我会处理所有这些事情,但我卡住了如何使用界面初始化点击侦听器,以便我在任何 xml 中定义并获取事件在我的 class.

我正在关注这个 link: https://developer.android.com/topic/libraries/data-binding/index.html

假设这是我的回收者视图的根xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="handlers" type="com.example.MyHandlers"/>
<variable name="user" type="com.example.User"/>
</data>

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}"
android:onClick="@{handlers::onClickFriend}"
//>>> i want to initialise interface for position/view instead of @{handlers::onClickFriend}.
  />
</LinearLayout>
</layout>

请给我link和解决方案,我将不胜感激。

您可以通过 user/position。如果你想在 clickListener 中传递位置,你必须将它作为变量传递给 xml 与用户相同,然后

android:onClick="@{() -> handlers.onClickFriend(user)}

<variable name="position" type="Integer"/>

然后

android:onClick="@{() -> handlers.onClickFriend(position)}