How do you display a Toast using Kotlin on Android?

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

    Try this

    In Activity

    Toast.makeText(applicationContext, "Test", Toast.LENGTH_LONG).show()
    

    or

    Toast.makeText(this@MainActiivty, "Test", Toast.LENGTH_LONG).show()
    

    In Fragment

    Toast.makeText(activity, "Test", Toast.LENGTH_LONG).show()
    

    or

    Toast.makeText(activity?.applicationContext, "Test", Toast.LENGTH_LONG).show()
    
    0 讨论(0)
  • 2021-01-30 16:21

    It's actually a part of Anko, an extension for Kotlin. Syntax is as follows:

    toast("Hi there!")
    toast(R.string.message)
    longToast("Wow, such a duration")
    

    In your app-level build.gradle, add implementation "org.jetbrains.anko:anko-common:0.8.3"

    Add import org.jetbrains.anko.toast to your Activity.

    0 讨论(0)
  • 2021-01-30 16:22

    Show a Toast not from the UI Thread, in a Fragment

    activity?.runOnUiThread {
            Toast.makeText(context, "Image saved to the Gallery", Toast.LENGTH_SHORT).show()
        }
    
    0 讨论(0)
  • 2021-01-30 16:23

    This is one line solution in Kotlin:

    Toast.makeText(this@MainActivity, "Its toast!", Toast.LENGTH_SHORT).show()
    
    0 讨论(0)
  • 2021-01-30 16:25

    Custom Toast with Background color Text size AND NO XML file inflated Try the code without setting the Background color

        fun theTOAST(){
    
        val toast = Toast.makeText(this@MainActivity, "Use View Person List",Toast.LENGTH_LONG)
        val view = toast.view
        view.setBackgroundColor(Color.TRANSPARENT)
        val text = view.findViewById(android.R.id.message) as TextView
        text.setTextColor(Color.BLUE)
        text.textSize = (18F)
        toast.show()
    }
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题