In your XML you can use the attribute onClick
so that they all make a call to the click method.
XML
<Button
android:id="@+id/buttonOne"
...
android:onClick="onButtonClick"/>
<Button
android:id="@+id/buttonTwo"
...
android:onClick="onButtonClick"/>
Activity
public void onButtonClick(View view) {
switch (view.getId()) {
case R.id.buttonOne: { break; }
case R.id.buttonTwo: { break; }
case R.id.buttonThree: { break; }
...
}
}
This way you can save some lines of code. Another thing, depending on what functions the buttons on your screen have, you can also use a Recyclerview, which will also save you a lot of code. But this will depend on the function exercised by each button, if they are very different, I believe you want to use the example of the same code, but if they arrive in the same end, you could use a Recylerview.
For example, if you want to open a screen for each button, you could use the RV and depending on the button clicked, return a Bundle to open the corresponding screen, and so on.
See if this Soen response helps: https://stackoverflow.com/a/40282194/1377664
– Sam
According to the link above I am obliged to create a Setonclicklistener for each button or check one by one through id.
– Richard Kulikowsky
Can you specify what went wrong? Because what you did works yes.
– LMaker