How do you display a Toast using Kotlin on Android?

AndroidKotlin

Android Problem Overview


In different Kotlin examples for Android I see toast("Some message...") or toastLong("Some long message"). For example:

view.setOnClickListener { toast("Click") }

As I understand, it is an Extension Function for Activity.

How and where do you define this toast() function so that you are able to use it throughout the project?

Android Solutions


Solution 1 - Android

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 - Android

This is one line solution in Kotlin:

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

Solution 3 - Android

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 - Android

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 - Android

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")

Solution 6 - Android

While using Anko with Kotlin, inside fragment use either:

 activity.toast("string message") 

or

 context.toast("string message")

or

 view.holder.context.toast("string message")

Solution 7 - Android

With this extension function for Toasts, you can call them in Activities as well as Fragments, you can pass this as Context for Activities or getApplication() for Fragments, also it's generated with Toast.LENGTH_SHORT as default, so you don't need to worry to pass it as a parameter, but you can overwrite it as well if you need.

Kotlin

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

Usage

showToast("John Doe")

if you want to override the duration.

showToast("John Doe", Toast.LENGTH_LONG)

Solution 8 - Android

A very simple extension.

Add this to a toast.kt file

import android.content.Context
import android.widget.Toast
import androidx.fragment.app.Fragment

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

inline fun Fragment.toast(message:()->String){
   Toast.makeText(this.context, message() , Toast.LENGTH_LONG).show()
}

then you'll have

toast {
   "Hello World"
}

in both fragment & activity.

Solution 9 - Android

I have found very easy way to Toast from given link https://gist.github.com/felipearimateia/ee651e2694c21de2c812063980b89ca3. In this link Activity is used instead of Context. Try it.

Solution 10 - Android

Show a Toast not from the UI Thread, in a Fragment

activity?.runOnUiThread {
        Toast.makeText(context, "Image saved to the Gallery", Toast.LENGTH_SHORT).show()
    }

Solution 11 - Android

Android Toast for Kotlin

> Activity

Toast.makeText(applicationContext, "message...", Toast.LENGTH_SHORT).show()

> Fragment

Toast.makeText(activity, "message...", Toast.LENGTH_SHORT).show()

Solution 12 - Android

It's simply an extension function for Context (like other pointed out already).

You can find a lot of pre-defined android extension functions in Anko, which is probably what many of the tutorials use as well.

Solution 13 - Android

Just to add on @nhaarman's answer --> you probably want to add the resourceId support as well

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

Solution 14 - Android

Download source code from here (Custom Toast In Android Kotlin )

fun Toast.createToast(context: Context, message: String, gravity: Int, duration: Int, backgroucolor: String, imagebackgroud: Int) {
        val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        /*first parameter is the layout you made
        second parameter is the root view in that xml
         */
        val layout = inflater.inflate(R.layout.custom_toast, (context as Activity).findViewById(R.id.custom_toast_container))

        layout.findViewById(R.id.tv_message).text = message
        layout.setBackgroundColor(Color.parseColor(backgroucolor))
        layout.findViewById(R.id.iv_image).iv_image.setImageResource(imagebackgroud)
        setGravity(gravity, 0, 100)
        setDuration(Toast.LENGTH_LONG);

        setView(layout);
        show()
    }

Thanks!

Solution 15 - Android

the way I use it simply creating an Object/Class

object UtilKotlin {
    fun showMessage(context: Context, message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }
}

and calling the method

UtilKotlin.showMessage(activity, "Sets 0 !") // in activity trying this

Solution 16 - Android

Custom Toast with Background color Text size AND NO XML file inflated Try the code without setting the Background color

    fun theTOAST(){

    val toast = Toast.makeText(this@MainActivity, "Use View Person List",Toast.LENGTH_LONG)
    val view = toast.view
    view.setBackgroundColor(Color.TRANSPARENT)
    val text = view.findViewById(android.R.id.message) as TextView
    text.setTextColor(Color.BLUE)
    text.textSize = (18F)
    toast.show()
}

Solution 17 - Android

Here is extension of toast for activity or fragment

fun showToast(context: Context,@StringRes string : Int, duration: Int = Toast.LENGTH_SHORT){
  Toast.makeText(context,string,duration).show()
 }


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


inline fun Fragment.toast(message: () -> String, duration: () -> Int = { Toast.LENGTH_LONG }){
 Toast.makeText(this.context,message(),duration()).show()
}


inline fun AppCompatActivity.toast(message: () -> String, duration: () -> Int = { Toast.LENGTH_LONG }){
 Toast.makeText(this.applicationContext,message(),duration()).show()
}

If you want simple toast just call first method both fragment and activity

 showToast(yourContext,"your message")  or showToast(yourContext,"your message",1200L)

Or

toast {
 "Your message"
}

Or

toast({"your message"}) or toast({"your messge"},{your duration = 1200L})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - AndroidnhaarmanView Answer on Stackoverflow
Solution 2 - AndroidZeero0View Answer on Stackoverflow
Solution 3 - AndroidMuzView Answer on Stackoverflow
Solution 4 - AndroidThe BalaView Answer on Stackoverflow
Solution 5 - AndroidAzizView Answer on Stackoverflow
Solution 6 - Androidvishnu bennyView Answer on Stackoverflow
Solution 7 - AndroidGastón SaillénView Answer on Stackoverflow
Solution 8 - AndroidIan ElvisterView Answer on Stackoverflow
Solution 9 - AndroidKhyati VaraView Answer on Stackoverflow
Solution 10 - AndroidnorbDEVView Answer on Stackoverflow
Solution 11 - AndroidAftab AlamView Answer on Stackoverflow
Solution 12 - AndroidLovisView Answer on Stackoverflow
Solution 13 - AndroidAlgarView Answer on Stackoverflow
Solution 14 - AndroidDeepshikha PuriView Answer on Stackoverflow
Solution 15 - AndroidSamirView Answer on Stackoverflow
Solution 16 - AndroidVectorView Answer on Stackoverflow
Solution 17 - AndroidTarif ChakderView Answer on Stackoverflow