How do you display a Toast using Kotlin on Android?

Solution 1:

It can be an extension function for Context:

fun Context.toast(message: CharSequence) = 
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

You can place this anywhere in your project, where exactly is up to you. For example, you can define a file mypackage.util.ContextExtensions.kt and put it there as a top level function.

Whenever you have access to a Context instance, you can import this function and use it:

import mypackage.util.ContextExtensions.toast

fun myFun(context: Context) {
    context.toast("Hello world!")
}

Solution 2:

This is one line solution in Kotlin:

Toast.makeText(this@MainActivity, "Its a toast!", Toast.LENGTH_SHORT).show()

Solution 3:

It's actually a part of Anko, an extension for Kotlin. Syntax is as follows:

toast("Hi there!")
toast(R.string.message)
longToast("Wow, such a duration")

In your app-level build.gradle, add implementation "org.jetbrains.anko:anko-common:0.8.3"

Add import org.jetbrains.anko.toast to your Activity.

Solution 4:

Try this

In Activity

Toast.makeText(applicationContext, "Test", Toast.LENGTH_LONG).show()

or

Toast.makeText(this@MainActiivty, "Test", Toast.LENGTH_LONG).show()

In Fragment

Toast.makeText(activity, "Test", Toast.LENGTH_LONG).show()

or

Toast.makeText(activity?.applicationContext, "Test", Toast.LENGTH_LONG).show()

Solution 5:

If you don't want to use anko and want to create your own Toast extension. You can create inline(or without inline) extensions defined in a kotlin file(with no class) and with that you can access this function in any class.

inline fun Context.toast(message:String){
   Toast.makeText(this, message , duration).show()
}

Usage:

In Activity,

toast("Toast Message")

In Fragment,

context?.toast("Toast Message")