android - 如何在范围内使 `this`引用Kotlin Android Extension类型类?

标签 android kotlin kotlin-android-extensions

我有如下代码

        recycler_view.apply {
            // Some other code
            LinearSnapHelper().attachToRecyclerView(this)   
        }

如果我想使用apply,下面的this错误输出
        recycler_view.apply {
            // Some other code
            LinearSnapHelper().apply {
                  .attachToRecyclerView(this) // This will error because `this` is LinearSnapHelper()
            }
        }

我尝试了this@RecyclerView仍然错误
        recycler_view.apply {
            // Some other code
            LinearSnapHelper().apply {
                  .attachToRecyclerView(this@RecyclerView) // Still error
            }
        }

我尝试了this@recycler_view仍然错误
        recycler_view.apply {
            // Some other code
            LinearSnapHelper().apply {
                  .attachToRecyclerView(this@recycler_view) // Still error
            }
        }

this称为recycler_view的语法是什么?

注意:我可以执行以下操作,但是就像学习如何在this中拥有apply一样,它指的是Kotlin Android Extension类型类。
        recycler_view.apply {
            // Some other code
            LinearSnapHelper().apply {
                // Some other code
            }.attachToRecyclerView(this)
        }

最佳答案

在这种情况下,您可以将显式标签应用于外部lambda:

recycler_view.apply recycler@{
    // Some other code
    LinearSnapHelper().attachToRecyclerView(this@recycler)   
}

但是嵌套apply块看起来并不惯用,可能会造成混淆,我建议对recycler_view使用其他作用域函数,例如let:
recycler_view.let { recycler ->
    // Some other code
    LinearSnapHelper().attachToRecyclerView(recycler)   
}

关于android - 如何在范围内使 `this`引用Kotlin Android Extension类型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62371582/

相关文章:

Android,生成数字 Assets 链接 : keystore file for signing the app

android left join query with room

java - Android 无法发送多播 UDP 数据报

android - Kotlin + MVP - 意外覆盖

android - android中的垂直进度条

java - 如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

android - 使用 Kotlin Android Extensions 以编程方式扩展布局

android - 布局位于库模块中时合成 View 的未解决引用

database - android SQLite 与平面文件

java - 通知抽屉似乎已满 - 新通知被丢弃