Android Button OnClick Example

android.widget.Button is a frequently used widget in android application. You can add as many buttons as you need in a layout view object. But how to listen and response the click event when user click the buttons? This example will tell you how.

1. Listen And Response Button Click Event.

You have two methods to response button click event as below.

  1. Create a View.OnClickListener object and assign the object to the button instance use setOnClickListener method.
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ......
        }
    });
  2. Make the activity implements View.OnClickListener interface and override onClick(View view) method. You also need to set this activity as the on click listener for the buttons.
    public class ButtonActivity extends AppCompatActivity implements View.OnClickListener{
    
          @Override
          public void onClick(View view) {
              .........
          }
    }

2. Android Button OnClick Event Listener Example.

android button onclick example

There are three buttons in this example. The first two buttons are added in the layout xml file. The third green button is added in java source code. Click each button will popup a toast message.

3. Android Button OnClickListener Example Source Files.

This example contains only two source files.

  1. Main activity java file.
  2. Main activity layout xml file.

3.1 Main Activity Java File.

ButtonActivity.java

package com.dev2qa.androidfragment;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ButtonActivity extends AppCompatActivity implements View.OnClickListener{

    private LinearLayout linearLayout = null;

    // Button1 and button2 is added in layout xml file.
    private Button button1 = null;
    private Button button2 = null;

    private Context context = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button);

        setTitle("dev2qa.com - Android Button Example.");

        initControls();

        // Button3 is created in java code dynamically.
        // Create button3 in code.
        Button button3 = new Button(context);
        button3.setText("Button Three Is Added In Code");
        button3.setTextSize(20);
        button3.setAllCaps(false);
        button3.setBackgroundColor(Color.GREEN);

        // Add a OnClickListener object to button3.
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast toast = Toast.makeText(context, "You clicked button three.", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        });

        // Add button3 to the wrapper linear layout object to show it.
        linearLayout.addView(button3);
    }


    /* Initialise layout and button components. */
    private void initControls()
    {
        if(linearLayout == null)
        {
            linearLayout = (LinearLayout)findViewById(R.id.button_layout);
        }

        if(button1 == null)
        {
            button1 = (Button)findViewById(R.id.button_1);
        }

        if(button2 == null)
        {
            button2 = (Button)findViewById(R.id.button_2);
        }

        if(context == null)
        {
            context = getApplicationContext();
        }

        /* Must set the on click listener to this activity,
           otherwise the override onClick method will bot be invoked.*/
        linearLayout.setOnClickListener(this);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);

    }


    /* This method is called when any of the activity's view components is clicked. */
    @Override
    public void onClick(View view) {
        if(view != null)
        {
            String message = "";

            // Get view component id.
            int id = view.getId();

            // Show different message when click different view component.
            if(id == R.id.button_1)
            {
                message = "Button one is clicked.";
            }else if(id == R.id.button_2)
            {
                message = "Button two is clicked.";
            }else if(id == R.id.button_layout)
            {
                message = "You clicked button layout.";
            }

            // Create the toast popup message.
            Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }
}

3.2 Main Activity Layout Xml File.

Two buttons are wrapped by LinearLayout view object.

READ :   How To Fix Unable To Access Android Sdk Add-on List When Run Android Studio For The First Time

activity_button.xml

<LinearLayout
    android:id="@+id/button_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">

    <Button
        android:id="@+id/button_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button One"
        android:textAllCaps="false"
        android:textSize="20dp" />

    <Button
        android:id="@+id/button_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button Two"
        android:textAllCaps="false"
        android:textSize="20dp" />

</LinearLayout>

Reference

  1. Android LinearLayout Example
  2. Android LinearLayout OnTouchListener OnClickListener Example

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.