The Wayback Machine - https://web.archive.org/web/20240708100619/https://www.geeksforgeeks.org/button-in-kotlin/
Open In App

Button in Android

Last Updated : 16 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio.

The Class Hierarchy of the Button Class in Kotlin


Kotlin_Button


XML Attributes of Button Widget

XML Attributes

Description

android:idUsed to specify the id of the view.
android:textUsed to the display text of the button.
android:textColorUsed to the display color of the text.
android:textSizeUsed to the display size of the text.
android:textStyleUsed to the display style of the text like Bold, Italic, etc.
android:textAllCapsUsed to display text in Capital letters.
android:backgroundUsed to set the background of the view.
android:paddingUsed to set the padding of the view.
android:visibilityUsed to set the visibility of the view.
android:gravityUsed to specify the gravity of the view like center, top, bottom, etc

Example

In this example step by step demonstration of creating a Button will be covered. The application will consist of a button that displays a toast message when the user taps on it.

Note: Following steps are performed on Android Studio version 4.0

Step 1: Create a new project

  1. Click on File, then New => New Project.
  2. Choose “Empty Activity” for the project template.
  3. Select language as Kotlin.
  4. Select the minimum SDK as per your need.

Step 2: Modify the strings.xml file

Navigate to the strings.xml file under the “values” directory of the resource folder. This file will contain all strings that are used in the Application. Below is the appropriate code.

strings.xml
<resources>
    <string name="app_name">GfG | Button In Kotlin</string>
    <string name="btn">Button</string>
    <string name="message">Hello Geeks!! This is a Button.</string>
</resources>

 
Step 3: Modify the activity_main.xml file

Add a button widget in the layout of the activity. Below is the code of the activity_main.xml file which does the same.  

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"
    android:background="#168BC34A"
    tools:context=".MainActivity">

    <!-- Button added in the activity -->
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:text="@string/btn"
        android:textColor="@android:color/background_light"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 
Step 4: Accessing the button in the MainActivity file

Add functionality of button in the MainActivity file. Here describe the operation to display a Toast message when the user taps on the button. Below is the code to carry out this task. 

Java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        // storing ID of the button
        // in a variable
        Button button = (Button)findViewById(R.id.button);

        // operations to be performed
        // when user tap on the button
        if (button != null) {
            button.setOnClickListener((View.OnClickListener)(new View.OnClickListener() {
                    public final void onClick(View it) {

                    // displaying a toast message
                    Toast.makeText((Context)MainActivity.this, R.string.message, Toast.LENGTH_LONG).show();
                }
            }));
        }
    }
}
Kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // storing ID of the button
        // in a variable
        val button = findViewById<Button>(R.id.button)

        // operations to be performed
        // when user tap on the button
        button?.setOnClickListener()
        {
            // displaying a toast message
            Toast.makeText(this@MainActivity, R.string.message, Toast.LENGTH_LONG).show() }
    }
}

Output:
 



Previous Article
Next Article

Similar Reads

How to use ImageView as a Button in Android?
ImageView is used when we want to work with images or we want to display them in our application. So, this article will give you a complete idea of using an ImageView as a Button in android studio. So, without wasting further time let's go to the article and read how we can achieve this task. What we are going to develop in this article? We will be
3 min read
How to Create Custom Loading Button By Extending ViewClass in Android?
In this article, we are going to create a custom loading button by extending the View class and animate properties of the custom button once it’s clicked. We had come across many times while downloading any file and keeping our eyes on the downloading progress. Here we will only create that custom button with animation. A sample GIF is given below
5 min read
Motion Layout Button in Android Jetpack Compose
Motion Layout is a special version of Constraint layout. With the help of motion layout, we can add animations to the widgets within the layout and change the position of that widget dynamically. In this article, we will take a look at How to implement Motion Layout animation on buttons in Android using Jetpack compose. What we are going to build i
8 min read
Ripple Effect on Android Button
The touch feedback in Android is a must whenever the user clicks on the item or button ripple effect when clicking on the same, gives confidence to the user that the button has been clicked so that they can wait for the next interaction of the app. So in this article, we are going to discuss what type of ripples can be implemented and where it can
4 min read
Theming Floating Action Button with Bottom Navigation Bar in Android
In the previous article How to Add a Floating Action Button to Bottom Navigation Bar in Android?, it's well discussed how to add the Floating Action Button to the Bottom Navigation Bar in Android. Now to increase the UI/UX experience theming also can be done for the Bottom Navigation Bar. So in this article, it's been discussed how we can theme the
4 min read
How to change Input Method Action Button in Android?
In this article, IME(Input Method Action) Option is changed in android according to our requirement. Input Method Action Button is located in the bottom right corner of the soft keyboard. By default, the system uses this button for either a Next or Done action unless your text field allows multi-line text, in which case the action button is a carri
2 min read
Different Ways to Programmatically Restart an Android App on Button Click
Sometimes we want to refresh an Activity, but there it is not possible to refresh. In that place, if we restart our app then it automatically gets refreshed. Also, we can use this to restart our app whenever it crashes. Most of the time when we open any app then it fetches all the data currently available. But if in the meantime if more data is upd
3 min read
Floating Action Button (FAB) in Android with Example
The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app's UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this a
8 min read
Extended Floating Action Button in Android with Example
In the Floating Action Button (FAB) article, we have discussed on Normal/Regular Floating Action Button and Mini Floating Action Button. In this article, let's discuss and implement an Extended Floating Action Button in android which extends when clicked and shrinks when closed and also shows the information about the sub-floating action button for
10 min read
How To Avoid Snackbar Overlap Floating Action Button in Android?
If one has implemented the Floating Action Button (FAB) in his android application and also there exists a Snackbar implementation in the same application, then the Snackbar is definitely going to overlap the Floating Action Button. Prerequisite: Floating Action Button (FAB) in Android with ExampleHow to add a Snackbar in Android Have a look at the
4 min read