Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you display a Toast using Kotlin on Android?

Tags:

android

kotlin

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?

like image 500
Andrew Avatar asked Apr 24 '16 16:04

Andrew


People also ask

How do you show toast on Android?

Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.

How do I print a toast message on android?

Toast toast=Toast. makeText(getApplicationContext(),"Hello Javatpoint",Toast. LENGTH_SHORT);

How do you show toast in fragment in Kotlin?

You can use the makeText() method to instantiate a Toast object: The application or activity Context . The text to appear on the screen to the user. The duration to show toast on screen.


4 Answers

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!") } 
like image 118
nhaarman Avatar answered Sep 22 '22 10:09

nhaarman


This is one line solution in Kotlin:

Toast.makeText(this@MainActivity, "Its a toast!", Toast.LENGTH_SHORT).show() 
like image 23
Zeero0 Avatar answered Sep 23 '22 10:09

Zeero0


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.

like image 37
Muz Avatar answered Sep 20 '22 10:09

Muz


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()
like image 43
The Bala Avatar answered Sep 21 '22 10:09

The Bala