How to Set Different Events on Successive Clicks on Same Button in Android

Introduction

 
This article explains how to set various events on successive clicks on the same button in Android.
 
Procedure
  1. Start Eclipse IDE.
  2. Create a new project.
  3. Create a MainActivity.java file.
  4. Create an activity_main.xml file for layout design.
  5. Add a button in the XML layout.
  6. Then look up the button by its id in the MainActivity.java file.
  7. Add various events in the onClick function.
The following is the code.
 
MainActivity.java
  1. package com.example.doubleclickevent;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.view.Menu;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.Toast;  
  9. public class MainActivity extends Activity implements OnClickListener {  
  10.  Button b1;  
  11.  int i = 0;  
  12.  @Override  
  13.  protected void onCreate(Bundle savedInstanceState) {  
  14.   super.onCreate(savedInstanceState);  
  15.   setContentView(R.layout.activity_main);  
  16.   b1 = (Button) findViewById(R.id.btn);  
  17.   b1.setOnClickListener(this);  
  18.  }  
  19.  @Override  
  20.  public boolean onCreateOptionsMenu(Menu menu) {  
  21.   getMenuInflater().inflate(R.menu.main, menu);  
  22.   return true;  
  23.  }  
  24.  public void onClick(View v) {  
  25.   if (i == 0) {  
  26.    Toast.makeText(getApplicationContext(), "hiii abhi"1000).show();  
  27.    i++;  
  28.   } else if (i == 1) {  
  29.    Toast.makeText(getApplicationContext(), "hello"1000).show();  
  30.    i = 0;  
  31.   }  
  32.  }  
activity_main.xml
  1. <RelativeLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.   
  5. android:layout_width="match_parent"  
  6. android:layout_height="match_parent"  
  7. android:paddingBottom="@dimen/activity_vertical_margin"  
  8. android:paddingLeft="@dimen/activity_horizontal_margin"  
  9. android:paddingRight="@dimen/activity_horizontal_margin"  
  10. android:paddingTop="@dimen/activity_vertical_margin"  
  11. tools:context=".MainActivity" >  
  12.       
  13. <Button android:layout_width="wrap_content"  
  14.   android:layout_height="wrap_content"  
  15.   android:text="ok"  
  16.   android:id="@+id/btn"/>  
  17.     
  18. </RelativeLayout> 
Output
 
On the first click:
 
On 1st click
 
On the second click:
 
On 2nd click