gpt4 book ai didi

android - ViewBinding vs Kotlin Android Extensions 与合成 View

转载 作者:行者123 更新时间:2023-12-04 01:55:45 25 4
gpt4 key购买 nike

新的ViewBinding怎么样与 Kotlin Android Extensions 进行比较与合成 View 绑定(bind)?
除了新的 ViewBindings 提供的 NullSafety 和 TypeSafety 之外,我们为什么要考虑放弃 Kotlin 在 Views 上使用合成绑定(bind)的方式?
新的 ViewBinding 是否更高效,因为它预先生成了 Binding 类?

最佳答案

让我们回顾一下两者。

配置

Kotlin Android 扩展

  • 导入适当的布局合成扩展:import kotlinx.android.synthetic.main.<layout>.*
  • 通过 id 引用代码中的 View :textView.text = "Hello, world!" .这些扩展适用于:Activities , FragmentsViews .

  • View 绑定(bind)
  • 在你的类中创建绑定(bind)引用:private lateinit var binding
    YourClassBinding
  • 为您的装订充气 binding = YourClassBinding.inflate(layoutInflater)里面 ActivityonCreate并调用setContentView(binding.root) , 或在 Fragment 中充气的onCreateView然后返回:return binding.root
  • 通过使用其 id binding.textView.text = "Hello, world!" 绑定(bind)来引用代码中的 View


  • 类型安全

    Kotlin Android 扩展 View 绑定(bind) 根据定义是类型安全的,因为引用的 View 已经转换为适当的类型。

    零安全

    Kotlin Android 扩展 View 绑定(bind) 都是空安全的。 ViewBinding 在这里没有任何优势 .如果是 凯航 ,如果 View 仅存在于某些布局配置中,IDE 会为您指出:

    enter image description here

    因此,您只需将其视为 Kotlin 中的任何其他可为空的类型,错误就会消失:

    enter image description here

    应用布局更改

    如果是 Kotlin Android 扩展 ,布局更改立即转化为合成扩展的生成,因此您可以立即使用它们。如果是 View 绑定(bind) ,你必须建立你的项目

    布局使用不正确

    如果是 Kotlin Android 扩展 ,可能会导入不正确的布局合成扩展,从而导致 NullPointerException .这同样适用于 View 绑定(bind) , 因为我们可以导入错误的 Binding类(class)。虽然,它是
    比不正确的类名更容易忽略不正确的导入,特别是如果布局文件以 Activity 命名时/ Fragment/ View , 所以 View 绑定(bind) 在这里占了上风。

    KAE 与 ViewBinding 的总结
  • 类型安全 - 画。
  • 零安全 - 画。
  • 样板代码 - 凯航 获胜。来自 Kotlin Android 扩展 documentation :

  • The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code.


  • 应用布局更改 - 凯航 获胜。与 相比,变化是即时的。 View 绑定(bind) .
  • 布局使用不正确 - View 绑定(bind)


  • 我认为对 存在很大的误解 View 绑定(bind) 替换 凯航 .人们听到大关键字并重复它们而无需事先验证。当然, View 绑定(bind) 是目前 Java 开发的最佳选择(替换 ButterKnife ),但与 相比没有或几乎没有优势凯航 在 Kotlin 中(参见 布局使用不正确 部分)。

    旁注:
    我相信 DataBinding 的人会喜欢 ViewBinding :)

    关于android - ViewBinding vs Kotlin Android Extensions 与合成 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58351239/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com