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="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">
 
 <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"/>

</LinearLayout>

Source for the Activity - AndroidButtonClickActivity.java

package com.as400samplecode;

import android.app.Activity;
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) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        Button button1 = (Button) findViewById(R.id.button1);
  button1.setOnClickListener(this);
  Button button2 = (Button) findViewById(R.id.button2);
  button2.setOnClickListener(this);
    
    }
 
 public void onClick(View v) {
  
  TextView responseText = (TextView) findViewById(R.id.responseText);
  
  switch (v.getId()) {
  case R.id.button1:
   responseText.setText("Clicked on Button 1\n bla bla bla ...");
   break;
  case R.id.button2:
   responseText.setText("Clicked on Button 2\n bla bla bla ...");
   break;
  
   // 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.