Reputation: 2779
I use earlier ButterKnife library. This is how I used the click event on multiple objects.
@OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(DoorView door) {
if (door.hasPrizeBehind()) {
Toast.makeText(this, "You win!", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try again", LENGTH_SHORT).show();
}
}
Without ButterKnife;
override fun onClick(v: View?) {
when (v!!.id) {
R.id.tv -> {
Toast.makeText(this, "You are click textview", Toast.LENGTH_SHORT).show()
}
R.id.btn -> {
Toast.makeText(this, "You are click button.", Toast.LENGTH_SHORT).show()
}
else -> {
}
}
}
Click the process what I can do. I want to do this with switch or when. Sounds like bad code writing individual setOnClickListener.
binding.btnFive.setOnClickListener { MyLog.log("five") }
//or
btnFour.setOnClickListener { MyLog.log("four") }
But i use now data binding. How do I do this with data binding?
What I was looking for;
when(binding){ //of course, this doesn't work. exemplary.
btnFirst->{}
btnSecond->{}
}
So I don't want to have to write setOnClickListener{}
so consistently. How do I do this?
Upvotes: 2
Views: 4416
Reputation: 15
first at kotlin you don't need any assigning view from layout you can use direct id as view which setcontentview.
Upvotes: 0
Reputation: 6245
To get View
id you have to call binding.btn.id
. But data binding suggests to use ViewModel
and and handling on click inside layout.xml
<Button
.....
android:onClick="@{()-> viewModel.btnClick()}"
..../>
You can find explanation at developer docs
Upvotes: 3
Reputation: 1611
Just same as without butterknife onClick code snippet
android { ... dataBinding { enabled = true } }
Only change
and in xml Put your xml in this tag
https://developer.android.com/topic/libraries/data-binding
Upvotes: 1