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

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 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

package com.example.doubleclickevent;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

 

public class MainActivity extends Activity implements OnClickListener

{

    Button b1;

    int i=0;

 

    @Override

    protected void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        b1=(Button) findViewById(R.id.btn);

        b1.setOnClickListener(this);

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu)

    {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

         return true;

    }

 

    public void onClick(View v)

    {

         // TODO Auto-generated method stub

         if(i==0)

         {

             Toast.makeText(getApplicationContext(), "hiii abhi", 1000).show();

             i++;

         }

         else if(i==1)

         {

             Toast.makeText(getApplicationContext(), "hello", 1000).show();

             i=0;

         }

    }

 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

  <Button android:layout_width="wrap_content"

  android:layout_height="wrap_content"

  android:text="ok"

  android:id="@+id/btn"/>

</RelativeLayout>

Output

On the first click:

On 1st click

On the second click:

On 2nd click