activity_main.xml
Full project with source code how to set OnClickListeners for multiple buttons and handle them all in one onClick method. Instead of passing an anonymous inner class to the setOnClickListener method, we will pass the activity itself and implement the OnClickListener interface into our MainActivity. We will then use a switch/case statement to check for the button IDs and handle the corresponding button click
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="tech.codingpoint.multipleonclicklistenerexample.MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button3" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button4" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button5" />
</LinearLayout>
MainActivity.java
package tech.codingpoint.multipleonclicklistenerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Button button3 = findViewById(R.id.button3);
Button button4 = findViewById(R.id.button4);
Button button5 = findViewById(R.id.button5);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Toast.makeText(this, "Button 1 clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(this, "Button 2 clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(this, "Button 3 clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button4:
Toast.makeText(this, "Button 4 clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button5:
Toast.makeText(this, "Button 5 clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}