o7planning

Android Button Tutorial with Examples

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- Android Button

In AndroidButton is a "user interface control" which is used to perform an action when the user clicks on it.
In the class hierarchy, Button is a subclass of TextView, so it inherits all the features of a TextView.
android:textAllCaps
By default, when displaying content, the text of Button will be turned into uppercase; therefore, you should set android:textAllCaps="false" to ensure that the text content will be correctly displayed as the original.

<Button
    android:id="@+id/button3"
    android:text="Alarm"
    android:drawableLeft="@drawable/icon_alarm"
    android:textAllCaps="false"
    ... />
android:gravity
The android:gravity attribute is used to set the text display position of a Button. Its value is a combination of the following values:
Constant in Java Value Description
Gravity.LEFT left  
Gravity.CENTER_HORIZONTAL center_horizontal  
Gravity.RIGHT right  
Gravity.CLIP_HORIZONTAL clip_horizontal  
Gravity.FILL_HORIZONTAL fill_horizontal  
     
Gravity.TOP top  
Gravity.CENTER_VERTICAL center_vertical  
Gravity.BOTTOM bottom  
Gravity.CLIP_VERTICAL clip_vertical  
Gravity.FILL_VERTICAL fill_vertical  
     
Gravity.START start  
Gravity.END end  
Gravity.CENTER center  
Gravity.FILL fill  

<Button
    android:id="@+id/button"
    android:gravity="center_horizontal|top"
    android:text="Text"
    ... />
Icon - android:drawableLef, android:drawableTop,..
Android allows you to add four icons into a Button through the attributes of android:drawableLef, android:drawableTop, android:drawableRight, android:drawableBottom, android:drawableStart, android:drawableEnd.

<Button
    android:id="@+id/button"
    android:drawableLeft="@drawable/icon_bus"
    android:drawableTop="@drawable/icon_railway"
    android:drawableRight="@drawable/icon_car"
    android:drawableBottom="@drawable/icon_boat"
    android:text="Text"
    ...  />
Android 4.1 started to support text layout differences among different languages. More specifically, in English, text is written from left to right, while in Arabic languages, text is from right to left.
LTR (Left to Right)
In LTR (Left to Right) layout mode: The android:drawableStart attribute will work in the same way as the android:drawableLeft, and the android:drawableEnd will work in the same way as the android:drawableRight.
RTL (Right to Left)
In RTL (Right to Left) layout mode: The android:drawableStart  attribute will work in the same way as the android:drawableRight, and android:drawableEnd  attribute will work in the same way as the​​​​​​​ android:drawableStart.

2- Button Click Event

Click event happens after the user presses down and releases the Button.
You can define the name of the method which will be called when the user clicks on the Button by using the android.onClick attribute.

<Button
    android:id="@+id/button_clickMe"
    android:onClick="onClickHandler"
    android:text="Click Me"
    ... />
Simultaneously create this method in MainActivity class.

// MainActivity

public void onClickHandler(View view)  {
    Toast.makeText(this, "You click on 'Click Me' button!", Toast.LENGTH_SHORT).show();
}
You can define the method that will be called when the user clicks on the Button by Java code:

this.buttonClickMe = (Button) this.findViewById(R.id.button_clickMe);

this.buttonClickMe.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "You click on 'Click Me' button!", Toast.LENGTH_SHORT).show();
    }
});

3- Button Long Click Event

Long Click events in Android happen when the user presses down and hold the View for a long time. Specifically, the event will happen at the LONG_PRESS_TIMEOUT milliseconds since the user presses it down.You can get the value of the LONG_PRESS_TIMEOUT from the ViewConfiguration.getLongPressTimeout() method.
The default duration of a Long-Click in Android is DEFAULT_LONG_PRESS_TIMEOUT milliseconds. The user can change the Long-Click duration in the Settings of the device, which will be applied for all applications in the system. Application developers are not able to change this value.
Constant
(private)
Method
Value
(Milliseconds)
DEFAULT_LONG_PRESS_TIMEOUT   500
  ViewConfiguration.getLongPressTimeout() 500 (default)
For example: Handling the event when the user Long Click in a Button by Java codes (Note that you cannot do this with XML).

this.buttonClickMe = (Button) this.findViewById(R.id.button_clickMe);


this.buttonClickMe.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        Toast.makeText(MainActivity.this, "You long click on 'Click Me' button!", Toast.LENGTH_SHORT).show();
        return true;
    }
});
If the user clicks on View for a long time (longer than LONG_PRESS_TIMEOUT milliseconds), that action can generate two consecutive events, Long-Click and Click.
The onLongClick(View) method returns a boolean value. Returning true means that you have consumed the Long-Click event, and the Click event which happens after that will be ignored. Otherwise, if the onLongClick(View) method returns the false value, it means the Click event which happens after that will be executed.

4- Example of Android Button

Here is a simple example: the user will enter two numbers, and click the Button to sum these two numbers.
Design the example interface:
Align the position of components in the interface:
Set ID, and Text for the components in the interface:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Number 1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_number1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Number 2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_number1" />

    <EditText
        android:id="@+id/editText_number2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/button_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Add"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_number2" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java

package org.o7planning.buttonexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText editTextNumber1;
    private EditText editTextNumber2;
    private Button buttonAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.editTextNumber1 = (EditText) this.findViewById(R.id.editText_number1);
        this.editTextNumber2 = (EditText) this.findViewById(R.id.editText_number2);

        this.buttonAdd = (Button) this.findViewById(R.id.button_add);

        this.buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add2Number();
            }
        });
    }


    private void add2Number()  {
        String str1 = this.editTextNumber1.getText().toString();
        String str2 = this.editTextNumber2.getText().toString();
        try {
            double value1 = Double.parseDouble(str1);
            double value2 = Double.parseDouble(str2);

            double result = value1 + value2;

            Toast.makeText(this, "Result: " + result, Toast.LENGTH_SHORT).show();
        } catch(Exception e)  {
            Toast.makeText(this, "Error: "+ e, Toast.LENGTH_SHORT).show();
        }
    }

}

View more Tutorials:

Maybe you are interested

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.