How do you display a Toast using Kotlin on Android?

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

    While using Anko with Kotlin, inside fragment use either:

     activity.toast("string message") 
    

    or

     context.toast("string message")
    

    or

     view.holder.context.toast("string message")
    
    0 讨论(0)
  • 2021-01-30 16:31

    Just to add on @nhaarman's answer --> you probably want to add the resourceId support as well

    fun Context.toast(resourceId: Int) = toast(getString(resourceId))
    fun Context.toast(message: CharSequence) = 
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    
    0 讨论(0)
  • 2021-01-30 16:35

    I have found very easy way to Toast from given link https://gist.github.com/felipearimateia/ee651e2694c21de2c812063980b89ca3. In this link Activity is used instead of Context. Try it.

    0 讨论(0)
提交回复
热议问题