In different Kotlin examples for Android I see toast("Some message...")
or toastLong("Some long message")
. For example:
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()
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.
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()
}
This is one line solution in Kotlin:
Toast.makeText(this@MainActivity, "Its toast!", Toast.LENGTH_SHORT).show()
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()
}
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")