Search code examples
javaandroidonclicklistener

How to handle onClick for many buttons which do same actions?


I have about 60 buttons and I want when click on any on them to do the same actions: get the text of the clicked button. check the text and if is correct disable it, otherwise display a toast. I want to avoid to have a switch with 60 cases. Is there a shorter way to do it?


Solution

  • Use ButterKnife and implememnt onclick as:

    @OnClick({ R.id.button1, R.id.button, R.id.button})//as many you want
    public void onButtonClick(Button button) {
      if (button.getText().equals("correctText")) {
        //Do whatever you want
      } else {
        Toast.makeText(this, "message", LENGTH_SHORT).show();
      }
    }