Android Button - Create a Button In Android with Kotlin and Java

Android button is a commonly used widget in the android applications. It is a widget which is used to perform click actions with in the UI screen. Example Navigate to other screens, Send Email, show Toast messages etc.
In this chapter we are going to create a simple Button in Android app 

  • Create a Button
  • Button Text
  • Button style
  • Button Click Events (OnClick, Long Click)
  • Different types of Buttons in Android
  • Show Toast message on button click
Android Button OnClick listener to show Toast Message

 

Create a Button

Create a Project in Android studio (File->New->New Project) choose Empty Activity template and finish all basic setup Open xml file, you will see default Textview in the file Now drag and drop Button widget from Pallet window

Sample code for button inside xml file would be like this

<?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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Attributes of Button in Android:

In Android each widget will contains some properties to perform actions with the widgets. Here we are going to discuss few properties of Button Widget.

id: id is an attribute used to uniquely identify a text Button. Below is the example code in which we set the id of a Button

<Button
        android:id="@+id/button" />

 

text: This attribute is used to set the text for the button, which will display on the button.

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />


gravity: The gravity attribute is an optional attribute which is used to control the alignment of the text like left, right, center, top, bottom, center_vertical, center_horizontal etc.

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:gravity="center_vertical" />

Set Text to the Button

We can set the Text to the button in two ways, by using the text property in the xml file and other way is inside the Java/Kotlin activity class 

To set the Text to the button inside activity class we will use the setText() method

Access Button inside activity class

We defined button in xml file and now we need to access that button inside activity class. To access this we will use the id attribute of the button and initialize it by using the findViewById() method

Kotlin code:
 

val button=findViewById<Button>(R.id.button)
        button.setText("Button 1")

Java Code:
 

 Button button=findViewById(R.id.button);
        button.setText("Button 1");

       

Button style setting

Each button is styled with the system's default button background, if we not happy with the default button styling and want to customize it to match our application's design

Set Button Text Color:  We can set the Text color to the button in two ways 
textColor: Using textColor attribute inside xml file we can set the text color

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textColor="#FFCCFF"
        android:gravity="center_vertical" />

setTextColor(): using this method we can set the color of button text inside activity class

Kotlin Code:

button.setTextColor(Color.RED)

Java Code:

button.setTextColor(Color.RED)

 

Button Text Size
textSize: textSize attribute is used to set the size of the text on Button. We can set the text size in sp(scale independent pixel) or dp(density pixel)

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textColor="#FFCCFF"
        android:textSize="25dp"
        android:gravity="center_vertical" />


Button Text Size in Activity class programmatically

Kotlin code:

button.textSize=25f

Java code:

 button.setTextSize(25F);

Button Style

background: background attribute is used to set the background of a Button. We can set a color or a drawable in the background of a Button

<Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textColor="#FFFFFF"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" 
        android:background="#FF0000"
        />

 

Set Button Background Color inside activity

We can also set the Button color programmatically using setBackgroundColor() method
 

Kotlin code

button.setBackgroundColor(Color.RED)

 

Java Code:

button.setBackgroundColor(Color.RED)

 

For the Material button we should use  android:backgroundTint="" to set the color for the button


Button Drawable
We add image to the button using drawable attribute. Add drawable to the button at left, right, top and bottom sides.
In xml
       

android:drawableLeft="@drawable/ic_bookmark"
        android:drawableRight="@drawable/ic_bookmark"
        android:drawableTop="@drawable/ic_bookmark"
        android:drawableBottom="@drawable/ic_bookmark"


        
Example        
        

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textColor="#FFFFFF"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:backgroundTint="#FF0000"
        android:drawableLeft="@drawable/ic_bookmark"
        />


        
To set the Drawable to the button in activity file will use setCompoundDrawablesWithIntrinsicBounds() method

Kotlin Code:

 button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_fav,0,0,0)


 
 Java Code: 

 button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_fav,0,0,0)


 
 Button OnClick
 If user click on a Button then Button object receive on-click event. To perform an event on the button, we will add "android:onClick" attribute to the <Button> element in XML layout.
 Now we need to create a method with the same inside activity file to handle the click event. The Activity hosting the layout must then implement the corresponding method.

For example – layout with a button using android:onClick

<Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textColor="#FFFFFF"
        android:gravity="center"
        android:backgroundTint="#FF0000"
        android:onClick="likeMe"
        />

The "likeme" method will be looks like below in activity file

Kotlin Code

fun likeMe(view: View) {
    Toast.makeText(applicationContext,"Liked",Toast.LENGTH_SHORT).show()
    }

 

Java Code
 

public void likeMe(View view)
    {
        Toast.makeText(getApplicationContext(),"Liked", Toast.LENGTH_SHORT).show()
    }


    Button onClickListener
To handle the button event programmatically we will add "onClickListener" event to the button using setOnClickListener() method
Kotlin Code:

button.setOnClickListener {

        }


        

Java Code:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
            }
        });

 

Button Long click 
We can perform some actions when long press on the button, this we can achieve by using button LongClickListener event
 

Kotli code:

button.setOnLongClickListener { 
            false
        }

 

Java Code:
 

button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return false;
            }
        });

Complete code for Android Button


xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Button Tutorial"
        android:textSize="35dp"
        android:layout_marginBottom="40dp"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Default"


        />
    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Color"
        android:textColor="#FFFFFF"
        android:gravity="center"
        android:backgroundTint="#FF0000"

        />
    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Drawable"
        android:textColor="#FFFFFF"
        android:gravity="center"
        android:backgroundTint="#FF0000"
        android:drawableLeft="@drawable/ic_fav"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Click"
        android:textColor="#FFFFFF"
        android:gravity="center"
        android:backgroundTint="#FF0000"
        android:onClick="likeMe"
        android:drawableLeft="@drawable/ic_fav"
        />

</LinearLayout>

Kotlin Code:

package com.example.androidbutton

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast

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

        val button=findViewById<Button>(R.id.button)
        button.setText("Button 1")
        button.setTextColor(Color.WHITE)

        button.textSize=25f
        button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_fav,0,0,0)
       // button.setBackgroundColor(Color.RED)

        button.setOnClickListener {
            likeMe(it)
        }

        button.setOnLongClickListener {
            true
        }
    }

    fun likeMe(view: View) {
    Toast.makeText(applicationContext,"Liked",Toast.LENGTH_SHORT).show()
    }
}

 

Java Code:

package com.example.androidbutton;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=findViewById(R.id.button);
        button.setText("Button 1");
        button.setTextColor(Color.WHITE);
        button.setBackgroundColor(Color.RED);
        button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_fav,0,0,0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                likeMe(view);
            }
        });
        button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return false;
            }
        });
    }
    public void likeMe(View view)
    {
        Toast.makeText(getApplicationContext(),"Liked", Toast.LENGTH_SHORT).show();
    }

}

 

Conculsion:

The above examples we learned introduction of the most commonly used UI controls our actual development, many controls have onClick () events, Button visibility...