Working with Button

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Android Button Example

android button

Android Button represents a push-button. The android.widget.Button is subclass of TextView class and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc.

Here, we are going to create two textfields and one button for sum of two numbers. If user clicks button, sum of two input values is displayed on the Toast.

Drag the component or write the code for UI in activity_main.xml

First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets palette as shown in the following figure.

android button example

The generated code for the ui components will be like this:

File: activity_main.xml
 
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <EditText  
  8.         android:id="@+id/editText1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentTop="true"  
  12.         android:layout_centerHorizontal="true"  
  13.         android:layout_marginTop="24dp"  
  14.         android:ems="10" />  
  15.   
  16.     <EditText  
  17.         android:id="@+id/editText2"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_alignLeft="@+id/editText1"  
  21.         android:layout_below="@+id/editText1"  
  22.         android:layout_marginTop="34dp"  
  23.         android:ems="10" >  
  24.   
  25.         <requestFocus />  
  26.     </EditText>  
  27.   
  28.     <Button  
  29.         android:id="@+id/button1"  
  30.         android:layout_width="wrap_content"  
  31.         android:layout_height="wrap_content"  
  32.         android:layout_centerHorizontal="true"  
  33.         android:layout_centerVertical="true"  
  34.         android:text="@string/Button" />  
  35.   
  36. </RelativeLayout>