【问题标题】:What does the angle bracket syntax mean after calling function findViewById in Kotlin在 Kotlin 中调用函数 findViewById 后尖括号语法是什么意思
【发布时间】:2021-01-16 19:34:24
【问题描述】:

这里是 Kotlin 新手;

我正在学习教程,https://developer.android.com/guide/topics/ui/floating-action-button

我在基本活动示例代码中看到了findViewById<FloatingActionButton>(R.id.fab),其中<FloatingActionButton> 部分让我感到厌烦。

 findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
            Snackbar.make(view, getString(R.string.MySnackBar), Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()

我很困惑,因为在其他示例代码中,我看到了 val rollButton: Button = findViewById(R.id.roll_button)

第一个findViewById&lt;FloatingActionButton&gt;是一个接口(?)如果是这样,为什么它需要一个,当第二个通过按原样传递按钮来工作时?

我是否误解了语法,或者错过了一个概念?

我确定我错过了这个拼图的一部分,但没有看到它。

非常感谢您提供的任何帮助或文档,您可以参考我的解释!

【问题讨论】:

  • 阅读泛型函数和泛型。

标签: android kotlin interface findviewbyid


【解决方案1】:

findViewById() 需要被告知期望的视图类型。您可以通过以下两种方式之一执行此操作:

  • 通过显式指定变量的类型
val button: Button = findViewById(R.id.button)
  • 通过将类型参数传递给findViewById()
val button = findViewById<Button>(R.id.button)

您当然可以将两者结合起来,但只需要一个。

我个人更喜欢第一个选项,因为它避免了platform types的推断。

【讨论】:

  • 谢谢您,先生,这是一个很好的解释!
  • 这回答了我的问题,但小的跟进,为什么它需要定义它期望的输出,这不是函数声明/签名的一部分,而不是我在哪里打电话吗?我认为可能有一个我不熟悉的更高级或现代的编程概念。再次感谢!
  • 函数声明如下所示:public final &lt;T extends View&gt; T findViewById(int id) {。重要的部分是&lt;T extends View&gt; T。在 Java 中,您总是在变量声明中提供此信息(例如,Button button = findViewById(...)),但在 kotlin 中,您有时依赖于类型推断,然后就没有什么可以告诉编译器该使用什么 T
  • 再次感谢!我很感激!
猜你喜欢
  • 2022-06-19
  • 2011-09-30
  • 2021-11-26
  • 2022-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 2023-03-15
相关资源
最近更新 更多