How to use data binding with "when" onClickListener in Kotlin

Viewed 3563

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?

3 Answers

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

first at kotlin you don't need any assigning view from layout you can use direct id as view which setcontentview.

Related