Andrey Andrey - 1 year ago 279
Android Question

Kotlin for Android. Toast

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 to define this toast() function and where (in what place) to be able to use it through the project?

Answer Source

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!")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download