如何在Android上使用Kotlin显示Toast? [英] How do you display a Toast using Kotlin on Android?

查看:734
本文介绍了如何在Android上使用Kotlin显示Toast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In different Kotlin examples for Android I see toast("Some message...") or toastLong("Some long message"). For example:

view.setOnClickListener { toast("Click") }

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

As I understand, it is an Extension Function for Activity.

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

How and where do you define this toast() function so that you are able to use it throughout the project?

推荐答案

它可以是Context的扩展功能:

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

您可以将其放置在项目中的任何位置,完全由您决定.例如,您可以定义文件mypackage.util.ContextExtensions.kt并将其作为顶级功能放置在此处.

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.

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

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

这篇关于如何在Android上使用Kotlin显示Toast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆