KTX toast扩展功能在哪里?

Where is the KTX toast extension function?

我从这篇文章 Even Sweeter Android development with Android KTX (https://www.kotlindevelopment.com/even-sweeter-android-ktx-kotlin/) 中了解到,Android toast 可以使用来自[=14= 的 KTX 进行简化]

Toast.makeText(context, R.string.toast_message, Toast.LENGTH_SHORT).show()

toast(R.string.toast_message)

我想在我的项目中尝试它,但我在 androidx.core:core-ktx:1.0.0 中找不到它。那么这个扩展函数在哪个依赖中呢?

你可以添加一个方法扩展来实现,据我所知,没有现成的。


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

    fun Context.toast(@StringRes resId: Int, duration: Int = Toast.LENGTH_SHORT) {
       Toast.makeText(this, this.resources.getText(resId), duration).show()
    }

添加这个

api "org.jetbrains.anko:anko-commons:0.10.1"

并像

一样使用它
toast(R.string.toast_message)

context.toast(R.string.toast_message)

看起来 Context.toast 扩展已从 ktx 库中删除 https://github.com/android/android-ktx/issues/143#issuecomment-417891391