In different Kotlin examples for Android I see toast("Some message...")
or toastLong("Some long message")
. For example:
Android Toast for Kotlin
Activity
Toast.makeText(applicationContext, "message...", Toast.LENGTH_SHORT).show()
Fragment
Toast.makeText(activity, "message...", Toast.LENGTH_SHORT).show()
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
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.
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.
fun Context.toast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_SHORT){
Toast.makeText(context, message , duration).show()
}
toast(this, "John Doe")
if you want to overwrite the duration.
toast(this, "John Doe", Toast.LENGTH_LONG)
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!
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!")
}