Android Button Example

By | October 21, 2013
Button is one of basic grahical user interface which is clickable, Android SDK Provides “android.widget.Button” class to create buttons for your android applications .

In this tutorial we will see how to add button to the activity , and also set the onclicklistener for the button to display the toast message .

Android Button ExampleAndroid Button onclickListener


Lets See Example

Project Detail

Project Name ButtonDemo
Package com.pavan.buttondemo
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

 1. XML Layout

 file: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">

<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"/>

</LinearLayout>

 2. Activity

 file: MainActivity.java

package com.pavan.buttondemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button my_button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_button = (Button) findViewById(R.id.button1);

// set listener for button
my_button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Toast.makeText(MainActivity.this, "You clicked Button",
Toast.LENGTH_SHORT).show();

}
});
}
}