onclicklistener for multiple buttons in android studio | How to implement multiple click listener in android studio ?

 

onclicklistener for multiple buttons in android studio | How to implement multiple click listener in android studio -

In this tutorial I will explain with example How to implements multiple click listener in android studio ?
Follow these steps to send your app link in android studio 

Step 1 -  Design Your Xml Layout
<?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:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="25dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:text="Button 1" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Button 2" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Button 3" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Button 4" />
</LinearLayout>

onclicklistener for multiple buttons in android studio | How to implement multiple click listener in android studio ?



Step 2 - In Your MainActivity.java file  extends AppCompatActivity implements View.OnClickListener

after this implements methods 
@Override
public void onClick(View v) {

}
}

Step 3 - find all button in onCreate Method - 

Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Button button3 = findViewById(R.id.button3);
Button button4 = findViewById(R.id.button4);

button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);

Step 4 - write this code in onClick Method

public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// write the code
break;
case R.id.button2:
// write the code 2
break;
case R.id.button3:
// write the code 3
break;
case R.id.button4:
// write the code 4
break;
}
}



Post a Comment

Previous Post Next Post