Android Button Click example

How to create a button in Android and capture the OnClick event

In this example we have created two buttons using XML layout resource and attached the onClick listener to them. When the user clicks on a button we add some text based on the screen based on the button that was clicked.

android button onclick example
android button onclick example

Source for the Screen Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:padding="5dp"
  android:text="Click on the buttons to add some text on the screen below"
  android:textAppearance="?android:attr/textAppearanceMedium" />
 <Button android:id="@+id/button1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_marginBottom="10dp"
  android:text="My Button 1" />
 <Button android:id="@+id/button2" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_marginBottom="10dp"
  android:text="My Button 2" />
 <TextView android:id="@+id/responseText" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:padding="5dp"
  android:text="" android:textAppearance="?android:attr/textAppearanceMedium"/>


Source for the Activity -

package com.as400samplecode;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AndroidButtonClickActivity extends Activity implements OnClickListener{
 public void onCreate(Bundle savedInstanceState) {
        Button button1 = (Button) findViewById(;
  Button button2 = (Button) findViewById(;
 public void onClick(View v) {
  TextView responseText = (TextView) findViewById(;
  switch (v.getId()) {
   responseText.setText("Clicked on Button 1\n bla bla bla ...");
   responseText.setText("Clicked on Button 2\n bla bla bla ...");
   // More buttons go here (if any) ...


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.