Android版Kotlin.吐司 [英] Kotlin for Android. Toast

查看:411
本文介绍了Android版Kotlin.吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

据我所知,它是活动的扩展功能.

As I understand it is an Extension Function for Activity.

如何定义此toast()函数以及在整个项目中的何处(在什么地方)可以使用它?

How to define this toast() function and where (in what place) to be able to use it through 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.吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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