繁体   English   中英

如何在 Android 上使用 Kotlin 显示 Toast?

[英]How do you display a Toast using Kotlin on Android?

在 Android 的不同 Kotlin 示例中,我看到toast("Some message...")toastLong("Some long message") 例如:

view.setOnClickListener { toast("Click") }

据我了解,它是Activity的扩展功能。

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

它可以是Context的扩展函数:

fun Context.toast(message: CharSequence) = 
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

您可以将其放置在项目中的任何位置,具体位置由您决定。 例如,您可以定义一个文件mypackage.util.ContextExtensions.kt并将其作为顶级函数放在那里。

只要您有权访问Context实例,就可以导入此函数并使用它:

import mypackage.util.ContextExtensions.toast

fun myFun(context: Context) {
    context.toast("Hello world!")
}

这是 Kotlin 中的一行解决方案:

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

它实际上是Anko的一部分,是 Kotlin 的扩展。 语法如下:

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

在您的应用程序级build.gradle ,添加implementation "org.jetbrains.anko:anko-common:0.8.3"

import org.jetbrains.anko.toast添加到您的活动中。

试试这个

活动中

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

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

在片段中

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

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

如果您不想使用anko并想创建自己的Toast扩展。 您可以创建在 kotlin 文件(没有类)中定义的内联(或不内联)扩展,并且您可以在任何类中访问此函数。

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

用法:

在活动中,

toast("Toast Message")

在片段中,

context?.toast("Toast Message")

Kotlin 中使用Anko时,在片段内部使用:

 activity.toast("string message") 

 context.toast("string message")

 view.holder.context.toast("string message")

一个非常简单的扩展。

将此添加到 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"
}

在片段和活动中。

我从给定的链接https://gist.github.com/felipearimateia/ee651e2694c21de2c812063980b89ca3找到了非常简单的 Toast 方法。 在此链接中,使用 Activity 而不是 Context。 试试吧。

使用Toasts 的这个扩展函数,您可以在活动和片段中调用它们,您可以将作为活动的ContextgetApplication()传递给片段,它也是使用Toast.LENGTH_SHORT作为默认生成的,因此您不需要担心将其作为参数传递,但如果需要,您也可以覆盖它。

科特林

fun Context.showToast(message: String, duration: Int = Toast.LENGTH_SHORT){
        Toast.makeText(context, message , duration).show()
    }

用法

showToast("John Doe")

如果你想覆盖持续时间。

showToast("John Doe", Toast.LENGTH_LONG)

片段中显示不是来自 UI 线程的 Toast

activity?.runOnUiThread {
        Toast.makeText(context, "Image saved to the Gallery", Toast.LENGTH_SHORT).show()
    }

适用于 Kotlin 的 Android Toast

活动

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

片段

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

它只是Context的扩展函数(就像其他人已经指出的那样)。

你可以在Anko 中找到很多预定义的 android 扩展函数,这可能也是很多教程使用的。

只是添加@nhaarman 的答案--> 您可能还想添加resourceId支持

fun Context.toast(resourceId: Int) = toast(getString(resourceId))
fun Context.toast(message: CharSequence) = 
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

从这里下载源代码( Android Kotlin 中的自定义 Toast

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

谢谢!

我使用它的方式只是创建一个Object / Class

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

并调用方法

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

带有背景颜色的自定义 Toast 文本大小且没有膨胀的XML文件尝试不设置背景颜色的代码

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

这是活动或片段的吐司扩展

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM