问题描述
有一个名为clickListener
的变量,它是android.view.View.OnClickListener
的变量。
我不知道如何在Android Studio的数据绑定中将值传递给clickListener
的变量android.view.View.OnClickListener
,您能告诉我吗?
还有,我不明白PlantAdapter.kt中的代码binding.setClickListener{...}
,你能告诉我吗?
list_item_plant.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="clickListener"
type="android.view.View.OnClickListener"/>
...
</data>
<com.google.samples.apps.sunflower.views.MaskedCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{clickListener}"
...
}
PlantAdapter.kt
class PlantAdapter : listadapter<Plant,RecyclerView.ViewHolder>(PlantDiffCallback()) {
...
class PlantViewHolder(
private val binding: ListItemPlantBinding
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.setClickListener {
binding.plant?.let { plant ->
navigatetoPlant(plant,it)
}
}
}
...
}
通常,我在 plain_activity_solution_2.xml 中定义一个数据绑定变量name
,我应该为其分配一个值,例如 PlainOldActivitySolution2.kt 。
因此,当我在 list_item_plant.xml 中定义数据绑定变量binding.name = "Ada"
时,应为其分配一个值,例如 PlantAdapter.kt clickListener / em>,
但是我在 PlantAdapter.kt 中找不到binding.clickListener=...
,相反,我只找到binding.clickListener=...
,为什么?
plain_activity_solution_2.xml
binding.setClickListener {...}
PlainOldActivitySolution2.kt
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="name"
type="String"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/plain_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@{name}"
...
}
解决方法
我不明白您要传递哪个变量以及原因。
但是要传递任何变量,您可以使用如下所示的lambda表达式:
android:onClick="@{() -> clickListener(someVariable,someOtherVariable)}"
如果需要视图,可以这样传递它:
android:onClick="@{(view) -> clickListener(view)}"
,
binding
有自己的类,通常,Android View.OnClickListener
仅传递Button
时传递的View
,您不能添加更多,但可以使用{ {1}}然后找到真实的对象并传递给您自己的侦听器。