How do you display a Toast using Kotlin on Android?

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

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

提交回复
热议问题