【问题标题】:Where is the KTX toast extension function?KTX toast扩展功能在哪里?
【发布时间】:2019-01-11 07:29:09
【问题描述】:

我从这篇文章 Even Sweeter Android development with Android KTX (https://www.kotlindevelopment.com/even-sweeter-android-ktx-kotlin/) 中了解到,可以使用来自

的 KTX 简化 Android toast
Toast.makeText(context, R.string.toast_message, Toast.LENGTH_SHORT).show()

toast(R.string.toast_message)

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

【问题讨论】:

  • but i could'nt find 添加到应用程序模块并将您的 xml 重命名为它的一部分 androidx.core:core-ktx:1.0.1

标签: android android-ktx


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    添加这个

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

    并像使用它一样

    toast(R.string.toast_message)
    

    context.toast(R.string.toast_message)
    

    【讨论】:

    • 最新版本是0.10.8
    • 如果我使用这个,我需要保留androidx.core:core-ktx:1.0.0吗?
    • 使用anko的。如何单独使用 kotlin-ktx?
    • anko 已弃用
    • 1. Anko 已弃用 2. 问题是关于 ktx lib
    【解决方案3】:

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

    
        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()
        }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      相关资源
      最近更新 更多