Home > Android > Android Widget – Button

Android Widget – Button

A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.

Button Attributes:

android:autoText - If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors.
android:drawableBottom - This is the drawable to be drawn below the text.
android:drawableRight - This is the drawable to be drawn to the right of the text.
android:editable - If set, specifies that this TextView has an input method.
android:text - This is the Text to display.
android:background - This is a drawable to use as the background.
android:contentDescription - This defines text that briefly describes content of the view.
android:id - This supplies an identifier name for this view,
android:onClick - This is the name of the method in this View's context to invoke when the view is clicked.
android:visibility - This controls the initial visibility of the view.

This example will take you through simple steps to show how to create your own Android application using Linear Layout and Button. First, create a layout in your layout folder.

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity">
    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="android-er.blogspot.com">
    <button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 1">
    </button><button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 2">

After Than Create Activity in your main src folder :

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
 protected void onCreate(Bundle savedInstanceState) {
  Button button1 = (Button)findViewById(R.id.button1);
  button1.setOnClickListener(new OnClickListener(){
   public void onClick(View arg0) {
      "Button 1 clicked",
  Button button2 = (Button)findViewById(R.id.button2);
 OnClickListener button2OnClickListener =
   new OnClickListener(){
    public void onClick(View v) {
       "Button 2 clicked",