首页 > 解决方案 > 有没有办法在片段中使用 Anko commons?

问题描述

在此处输入图像描述

我正在尝试toast{..}使用Anko library. 在活动中调用函数很简单toast{...},但我找不到在片段中调用函数的方法。

那么,有没有办法在片段中使用 Anko commons ?

标签: androidkotlinanko

解决方案


如果你浏览 Anko 的文档toast{..},它的实现是:

/**
 * Display the simple Toast message with the [Toast.LENGTH_SHORT] duration.
 *
 * @param message the message text resource.
 */

inline fun Context.toast(message: Int): Toast = Toast
        .makeText(this, message, Toast.LENGTH_SHORT)
        .apply {
            show()
        }

toast{..}是类的扩展函数Context。因此,它只能从继承自Context类的类中调用。

因此,要toast{...}在您的片段中使用,您必须使用activity?.toast("YOUR_TOAST_MESSAGE_HERE").


推荐阅读