How do you display a Toast using Kotlin on Android?

前端 未结 15 2217
遇见更好的自我
遇见更好的自我 2021-01-30 16:08

In different Kotlin examples for Android I see toast("Some message...") or toastLong("Some long message"). For example:



        
15条回答
  •  温柔的废话
    2021-01-30 16:15

    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.

    Kotlin

    fun Context.toast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_SHORT){
            Toast.makeText(context, message , duration).show()
        }
    

    Usage

    toast(this, "John Doe")
    

    if you want to overwrite the duration.

    toast(this, "John Doe", Toast.LENGTH_LONG)
    

提交回复
热议问题