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

is there a way to use Anko commons in the fragment?

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

所以,有没有办法在片段中使用Anko commons?

试试这个

实现这个

 implementation "org.jetbrains.anko:anko:0.10.6"

在您的片段中导入

import org.jetbrains.anko.support.v4.toast

在您的代码中

toast("string")

对我有用

如果你阅读 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{..}Contextclass的扩展函数。因此,只能从继承自 Context class.

的 class 调用它

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