98

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?

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Andrew
  • 36,676
  • 11
  • 141
  • 113

18 Answers18

165

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!")
}
nhaarman
  • 98,571
  • 55
  • 246
  • 278
109

This is one line solution in Kotlin:

Toast.makeText(this@MainActivity, "Its a toast!", Toast.LENGTH_SHORT).show()
Zeero0
  • 2,602
  • 1
  • 21
  • 36
49

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.

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
Muz
  • 5,866
  • 3
  • 47
  • 65
  • It looks like this is not officially supported by Android (I couldn't find any reference to Anko in the Android developer's website). Why could it be it so? It looks very intriguing. – Dakatine Sep 23 '18 at 14:45
  • 2
    It was from a while back, before Kotlin was officially supported by Google. Anko appears to be an unfinished project. The goal was to replace XML for layouts entirely, but they didn't do so well at it. A lot of the benefits of Anko were also gradually built into Kotlin. – Muz Sep 30 '18 at 22:59
  • thanks, that was very helpful. I now wonder why isn't this extension already provided by the Kotlin extensions for Android. Or is it and I can't find how to add it? :thinking: – Dakatine Oct 15 '18 at 21:42
21

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()
The Bala
  • 1,313
  • 1
  • 15
  • 23
6

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")
Aziz
  • 1,976
  • 20
  • 23
4

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.

Ian Elvister
  • 357
  • 3
  • 9
3

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")
Pavlos
  • 906
  • 1
  • 11
  • 29
vishnu benny
  • 998
  • 1
  • 11
  • 15
3

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)
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
  • why do you need to pass context again. you can absolutely use it as ```fun Context.toast(message: String, duration: Int = Toast.LENGTH_SHORT){ Toast.makeText(this, message , duration).show() }``` then ```toast("John Doe")``` or ```toast("John Doe", Toast.LENGTH_LONG)``` – Ian Elvister Apr 10 '21 at 15:42
  • Nice contribution @IanElvister, I will update the answer – Gastón Saillén Apr 10 '21 at 19:40
2

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.

Khyati Vara
  • 1,042
  • 13
  • 22
2

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()
    }
norbDEV
  • 4,795
  • 2
  • 37
  • 28
2

Android Toast for Kotlin

Activity

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

Fragment

Toast.makeText(activity, "message...", Toast.LENGTH_SHORT).show()
Aftab Alam
  • 1,969
  • 17
  • 17
1

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.

Lovis
  • 9,513
  • 5
  • 31
  • 47
1

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()
Algar
  • 5,734
  • 3
  • 34
  • 51
1

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!

Deepshikha Puri
  • 2,104
  • 22
  • 23
1

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
gmetax
  • 3,853
  • 2
  • 31
  • 45
Samir
  • 6,405
  • 5
  • 39
  • 42
1

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})
Tarif Chakder
  • 1,708
  • 1
  • 11
  • 10
0

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()
}
Vector
  • 3,066
  • 5
  • 27
  • 54
0

For Jetpack Compose use "context" from package "androidx.compose.runtime"

Toast.makeText(context, "Its a toast!", Toast.LENGTH_SHORT).show()
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Us3rL0sT
  • 3
  • 2