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?
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.
Toast toast=Toast. makeText(getApplicationContext(),"Hello Javatpoint",Toast. LENGTH_SHORT);
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.
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!") }
This is one line solution in Kotlin:
Toast.makeText(this@MainActivity, "Its a toast!", Toast.LENGTH_SHORT).show()
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With