Android Toast With Kotlin

Filed Under: Android

In this tutorial, we’ll be implementing Android Toasts in our application.

Android Toasts

Toasts are a UI widget that pops up on your screen for sometime in the form of a notification. They’re typically used when you want to show the user something that isn’t critical but might aid the user with what’s happening in the application currently.

The syntax to define a Toast is given below.


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

A Toast requires three arguments:

  • Context
  • Message
  • Duration

show() function is used to display the Toast on the screen.
We can customize the layout of the toast as well as its duration.
Let’s see that using the power of Kotlin with Android Toasts in the next section.

Project Structure

Create a New Android Studio Project. Ensure that you’ve included Kotlin support if you’re using Android Studio 3.0. Select an empty activity.
android-toasts-kotlin-project-structure

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

Layout

The layout for our activity_main.xml looks like this:


<?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. On each of the clicks, the Toasts would behave differently. The earlier mentioned Toast invocation looks a little verbose.
Let’s use Kotlin Extensions to bring some dynamicity.

Android Toasts Kotlin Extension Functions

Using Extension functions we can shorten our Toast invocation by setting some default values in the extension.
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. So to trigger a toast, the only thing you need to do is toast("Message").
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). applicationContext is the equivalent of getApplicationContext() in Java.

How to set a message that is a string resource from strings.xml?
String resources are of the type Int. So we need to set the parameter type as an Int.
Following extension function shows how to set a string 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 as:


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.
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 defined under. 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 in the screen.
show() triggers the Toast onto the screen.

MainActivity.kt Code

The code for the MainActivity.kt Kotlin 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 the Button that’s clicked.
On the Button clicks, we display the desired Toasts that were covered above.

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

android-toast-kotlin-output

This brings an end to this tutorial on Android Toasts. You can download the AndroidlyToasts Project from the link below.

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