Android Button OnClick Example

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

1. Listen And Response Button Click Event.

  1. You have two methods to respond button click event as below.
  2. Create a View.OnClickListener object and assign the object to the button instance using the setOnClickListener() method.
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ......
        }
    });
  3. 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.

  1. There are three buttons in this example.
  2. The first two buttons are added in the layout XML file. The third green button is added in the java source code.
  3. Click each button will pop up a toast message.
  4. Below is this example demo video ( android button onclick example ).

3. Android Button OnClickListener Example Source Files.

  1. This example contains only two source files.
  2. Main activity java file.
  3. Main activity layout XML file.

3.1 Main Activity Java File.

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

  1. Two buttons are wrapped by the LinearLayout view object.
  2. 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

2 thoughts on “Android Button OnClick Example”

Leave a Comment

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.