The following code is from the project sunflower.
There is variable named clickListener, it's a variable of android.view.View.OnClickListener.
I don't know how to pass a value to the variable clickListener of android.view.View.OnClickListener in data binding in Android Studio, could you tell me?
And more, I can't understand that the code binding.setClickListener{...} in PlantAdapter.kt, could you tell me?
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)
}
}
}
...
}
Added content
Normally, I define a data binding variable name in plain_activity_solution_2.xml, I should assign a value for it such as binding.name = "Ada" in PlainOldActivitySolution2.kt.
So when I define a data binding variable clickListener in list_item_plant.xml, I should assign a value for it such as binding.clickListener=... in PlantAdapter.kt,
But I can't find binding.clickListener=... in PlantAdapter.kt, instead I only find binding.setClickListener {...} , why?
plain_activity_solution_2.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="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}"
...
}
PlainOldActivitySolution2.kt
class PlainOldActivitySolution2 : AppCompatActivity() {
// Obtain ViewModel from ViewModelProviders
private val viewModel by lazy { ViewModelProviders.of(this).get(SimpleViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: PlainActivitySolution2Binding =
DataBindingUtil.setContentView(this, R.layout.plain_activity_solution_2)
binding.name = "Ada"
binding.lastName = "Lovelace"
}
...
}