If you want to reduce the coding lines then use View's OnClick() with switch statement
and if you want to handle separately all click (for easily understanding and maintaining code) then use separate all button's onClick().
Update:
If you have declared Buttons in your Activity layout xml file, than write attribute android:onClick=""
with same method name for all buttons and implement that method in your activity. Now you have one method for all buttons and in that method differentiate buttons with id.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 1" />
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 2" />
<Button android:id="@+id/button3"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 3" />
</LinearLayout>
Now in your Activity implement buttonOnClick
like,
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;
}
}
Or you can apply same switch case for dynamically added buttons in your activity,
like instead of buttonOnClick
you have to use implemented View's OnClickListerner's onClick
.