Search code examples
javaandroidviewlistener

How to create onClick method for multiple buttons using View Binding in Android studio?


This is simple to create onClick through view.getId()

public void buttonOnClick(View view)
{
 switch(view.getId())
 {
  case R.id.button1:
  // Code for button 1 click
  break;

  case R.id.button2:
  // Code for button 2 click
  break;

  case R.id.button3:
  // Code for button 3 click
  break;
 }
}

But is it possible to create it using view binding or I may as well implement listeners for each view instead?

P.S By view binding I mean using a new way of declaration of views

private ResultProfileBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ResultProfileBinding.inflate(getLayoutInflater());
    View view = binding.getRoot();
    setContentView(view);
}

Solution

  • TD LR implement listeners for each view instead

    From the Android docs here you will see that what view binding actually does is to create a class for your bind layout. That means that if you have a layout with 3 textviews for instance, your binding class will have 3 properties named after their ids

    • textview1
    • textview2
    • textview3

    each of which is already cast to the correct type (textView). basically eliminating the need for doing the code you post above, because if you think about it, what you are doing is getting the id of the view and the you do the cast but as I said the binding class has already done all that work for you.

    however if what you are trying to do is implement the same code in multiple views then I will suggest to abstract the shared code to a separate function and set that function on the views click listener.

    binding.textview1.setOnClickListener { sharedFunction() }
    binding.textview2.setOnClickListener { sharedFunction() }
    binding.textview3.setOnClickListener { sharedFunction() }