草庐IT

android - Kotlin Android View 绑定(bind) : findViewById vs Butterknife vs Kotlin Android Extension

coder 2023-05-08 原文

我正在尝试找出在 Kotlin 中进行 Android View 绑定(bind)的最佳方法。似乎有几个选项:

findViewById

val button: Button by lazy { findViewById<Button>(R.id.button) }

butterknife

https://github.com/JakeWharton/butterknife

@BindView(R.id.button) lateinit var button: Button

Kotlin Android 扩展

https://kotlinlang.org/docs/tutorials/android-plugin.html

import kotlinx.android.synthetic.main.activity_main.*

我对 java 领域的 findViewById 和 Butterknife 非常熟悉,但是 Kotlin 中每种 View 绑定(bind)方法的优缺点是什么?

Kotlin Android Extensions 是否与 RecyclerView + ViewHolder 模式配合得很好?

Kotlin Android Extensions 如何通过 include 处理嵌套 View 的 View 绑定(bind)?

ex:对于使用 activity_main.xml 的 Activity,如何访问 View custom1

activity_main.xml

<...>
    <include layout="@layout/custom" android:id="@+id/custom" />
</>

custom.xml

<...>
    <View android:id="@+id/custom1" ... />
    <View android:id="@+id/custom2" ... />
</>

最佳答案

在 Android 中有很多方法可以访问 View 。快速概览:

我的建议是:

  1. findViewById:老派。避免。
  2. ButterKnife:老派,但样板较少,并增加了一些功能。仍然缺乏编译时安全性。尽可能避免。
  3. Kotlin Synthetic:真正优雅的 findViewbyId 缓存版本。更好的性能和更少的样板,但仍然没有(真正的)编译时安全性。 Kotlin 1.8 将不再支持。尽可能避免。
  4. ViewBinding:Google 现在的推荐。它比数据绑定(bind)更快,并且可以防止 XML 中的逻辑错误(难以调试)。我对所有新项目都使用此选项。
  5. 数据绑定(bind):最通用的选项,因为它允许在 XML 中编写代码。仍在许多现有项目中使用。但是会减慢构建时间(像 ButterKnife 一样使用注释处理器),并且 XML 中的许多逻辑已经成为一种反模式。

另请参阅:https://www.youtube.com/watch?v=Qxj2eBmXLHg

有趣的是,Jake Wharton(ButterKnife 的原作者)现已加入 Google 并致力于 ViewBinding。

关于android - Kotlin Android View 绑定(bind) : findViewById vs Butterknife vs Kotlin Android Extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46482018/

有关android - Kotlin Android View 绑定(bind) : findViewById vs Butterknife vs Kotlin Android Extension的更多相关文章

随机推荐