Android Toast using Kotlin

Filed Under: Android

Android Toast is a UI widget that pops up on the screen for some time. It’s very similar to a notification, alert, or tooltip message. In this tutorial, we’ll learn how to create a Toast using Kotlin programming language.

When to use Toasts in Android app?

Toast messages are used to show the user something that isn’t critical but might help the user with what’s happening in the application currently. For example, giving a hint for a specific field in the form.

Syntax to Create a Toast

We can use the Toast class to create a toast message.

Toast.makeText(this, "Androidly Short Toasts", Toast.LENGTH_SHORT).show();

Toast.makeText(this, "Androidly Long Toasts", Toast.LENGTH_LONG).show();

Toast requires three arguments.

  1. Context
  2. Message
  3. Duration

The show() function is used to display the Toast on the screen.

We can customize the layout of the toast as well as its duration.

Android Toast using Kotlin

Let’s use the Kotlin to create an android app and create some toast messages.

First of all, create a new Android Studio Project and include the Kotlin support if you’re using Android Studio 3.0.

Select an empty activity.

android toast kotlin project structure

The custom_toast_layout.xml is used to define a custom layout for the Toast.

The layout for our activity_main.xml file is given in the following code snippet.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnShortToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SHORT TOAST"/>

    <Button
        android:id="@+id/btnLongToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LONG TOAST"/>


    <Button
        android:id="@+id/btnCustomToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CUSTOM TOAST"/>

</LinearLayout>

We’ve created three Buttons in our activity layout.

The toasts would behave differently on clicking each of the buttons.

The earlier mentioned Toast invocation looks a little verbose.

Let’s use Kotlin Extensions to create some dynamic toast messages.

Kotlin Extension Functions for Toasts

We can shorten our Toast invocation by setting some default values in the Kotlin extension functions.

The following function is an extension function that shall be used in our MainActivity.kt.

fun Context.toast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_SHORT){
        Toast.makeText(context, message , duration).show()
    }

We’ve set the default values of context and duration. If you call toast("Message"), it will trigger the toast message.

The applicationContext represents the context of the application. It makes the toast visible throughout the application. We can always change the default value to a different context(example: Activity context or a Fragment’s context). The applicationContext is the equivalent of getApplicationContext() in Java.

How to set a toast message from strings.xml?

String resources are of the type Int. So we need to set the parameter type as an Int.

The following extension function shows how to set strings.xml resource on a Toast.

fun Context.stringResToast(context: Context = applicationContext, message: Int, toastDuration: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(context, context.getString(message), toastDuration).show()
    }

To trigger the Toast, we just need to pass the string resource inside the function in our activity.

stringResToast(message = R.string.app_name)

Creating a Toast Programmatically

To create a Custom Toast programmatically we use a custom layout.

Following is the custom layout defined:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_container"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="#EAA"
    android:orientation="horizontal"
    android:padding="8dp"
    android:weightSum="1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_weight="0.2" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.8"
        android:textColor="#FFF" />
</LinearLayout>

To instantiate a Toast programmatically, we do val toast = Toast(this), where this is the Context.

Toasts are not views. Hence they can’t be added in the parent view using addView(). We need to inflate them.

The following function is used to create and trigger a Toast programmatically.

fun createCustomToast(message: String, imageSrc: Int) {
        val toast = Toast(this)
        toast.apply {

            val layout = linearLayout.inflate(R.layout.custom_toast_layout)

            layout.textView.text = message
            layout.imageView.setBackgroundResource(imageSrc)
            setGravity(Gravity.CENTER, 0, 0)
            duration = Toast.LENGTH_SHORT
            view = layout
            show()
        }
    }

fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
        return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
    }

We’ve created an inflate function to shorten our Toast layout declaration.

In the apply lambda expression, we inflate the layout in our Activity’s parent view using the inflate function.

Also, we set the text, image resource, duration as well as the gravity of the Toast.

The setGravity requires us to set the Gravity type: LEFT, RIGHT, CENTER, CENTER_HORIZONTAL, CENTER VERTICAL.

The second and third arguments are x and y offsets from the current position on the screen.

The show() function triggers the Toast onto the screen.

Kotlin Toast Code – MainActivity.kt

The code for the MainActivity.kt Kotlin’s class is given below.

package net.androidly.androidlytoasts

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.custom_toast_layout.view.*

class MainActivity : AppCompatActivity(), View.OnClickListener {


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

        btnShortToast.setOnClickListener(this)
        btnLongToast.setOnClickListener(this)
        btnCustomToast.setOnClickListener(this)

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnShortToast -> {
                toast(message = "Androidly Short Toasts")
                stringResToast(message = R.string.app_name)
            }
            R.id.btnLongToast -> {
                toast(message = "Androidly Long Toasts", toastDuration = Toast.LENGTH_LONG)
            }
            R.id.btnCustomToast -> {
                createCustomToast(message = "Androidly Custom Toast", imageSrc = R.mipmap.ic_launcher_round)
            }
        }
    }

    fun createCustomToast(message: String, imageSrc: Int) {
        val toast = Toast(this)
        toast.apply {

            val layout = linearLayout.inflate(R.layout.custom_toast_layout)

            layout.textView.text = message
            layout.imageView.setBackgroundResource(imageSrc)
            setGravity(Gravity.CENTER, 0, 0)
            duration = Toast.LENGTH_SHORT
            view = layout
            show()
        }
    }

    fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
        return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
    }

    fun Context.toast(context: Context = applicationContext, message: String, toastDuration: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(context, message, toastDuration).show()
    }

    fun Context.stringResToast(context: Context = applicationContext, message: Int, toastDuration: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(context, context.getString(message), toastDuration).show()
    }

}

In the above code, we’ve implemented the View.OnClickListener interface.

We’ve used a when statement to detect which button is clicked.

On the Button clicks, we display the specific Toasts that were defined in the earlier sections.

The output of the above application in action is given below.

android toast kotlin app output

You can download the project from the following link:

AndroidlyToasts

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages