How do you display a Toast using Kotlin on Android?

前端 未结 15 2403
遇见更好的自我
遇见更好的自我 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:20

    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!")
    }
    

提交回复
热议问题