如何在安卓系统上使用 Kotlin 显示祝酒词?

在不同的 Kotlin Android 例子中,我看到了 toast("Some message...")或者 toastLong("Some long message")。例如:

view.setOnClickListener { toast("Click") }

据我所知,它是 Activity的一个扩展函数。

如何以及在哪里定义这个 toast()函数,使您能够在整个项目中使用它?

145323 次浏览

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

It's simply an extension function for Context (like other pointed out already).

You can find a lot of pre-defined android extension functions in Anko, which is probably what many of the tutorials use as well.

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.

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

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.

This is one line solution in Kotlin:

Toast.makeText(this@MainActivity, "Its a toast!", Toast.LENGTH_SHORT).show()

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

Download source code from here (Custom Toast In Android Kotlin )

fun Toast.createToast(context: Context, message: String, gravity: Int, duration: Int, backgroucolor: String, imagebackgroud: Int) {
val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
/*first parameter is the layout you made
second parameter is the root view in that xml
*/
val layout = inflater.inflate(R.layout.custom_toast, (context as Activity).findViewById(R.id.custom_toast_container))


layout.findViewById(R.id.tv_message).text = message
layout.setBackgroundColor(Color.parseColor(backgroucolor))
layout.findViewById(R.id.iv_image).iv_image.setImageResource(imagebackgroud)
setGravity(gravity, 0, 100)
setDuration(Toast.LENGTH_LONG);


setView(layout);
show()
}

Thanks!

the way I use it simply creating an Object/Class

object UtilKotlin {
fun showMessage(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}

and calling the method

UtilKotlin.showMessage(activity, "Sets 0 !") // in activity trying this

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()
}

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

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.showToast(message: String, duration: Int = Toast.LENGTH_SHORT){
Toast.makeText(context, message , duration).show()
}

Usage

showToast("John Doe")

if you want to override the duration.

showToast("John Doe", Toast.LENGTH_LONG)

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

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()
}

Android Toast for Kotlin

Activity

Toast.makeText(applicationContext, "message...", Toast.LENGTH_SHORT).show()

Fragment

Toast.makeText(activity, "message...", Toast.LENGTH_SHORT).show()

一个非常简单的扩展。

将此文件添加到 toast.kt 文件

import android.content.Context
import android.widget.Toast
import androidx.fragment.app.Fragment


inline fun Context.toast(message:()->String){
Toast.makeText(this, message() , Toast.LENGTH_LONG).show()
}


inline fun Fragment.toast(message:()->String){
Toast.makeText(this.context, message() , Toast.LENGTH_LONG).show()
}

那你就有

toast {
"Hello World"
}

在碎片和活动中。

这是吐司的延伸部分

fun showToast(context: Context,@StringRes string : Int, duration: Int = Toast.LENGTH_SHORT){
Toast.makeText(context,string,duration).show()
}




inline fun Context.toast(message:()->String){
Toast.makeText(this, message() , Toast.LENGTH_LONG).show()
}




inline fun Fragment.toast(message: () -> String, duration: () -> Int = { Toast.LENGTH_LONG }){
Toast.makeText(this.context,message(),duration()).show()
}




inline fun AppCompatActivity.toast(message: () -> String, duration: () -> Int = { Toast.LENGTH_LONG }){
Toast.makeText(this.applicationContext,message(),duration()).show()
}

如果您想要简单的吐司,只需调用第一个方法,包括片段和活动

 showToast(yourContext,"your message")  or showToast(yourContext,"your message",1200L)

或者

toast {
"Your message"
}

或者

toast({"your message"}) or toast({"your messge"},{your duration = 1200L})