Kotlin Android 视图绑定:findViewById 与 Butterknife 与 Kotlin Android 扩展 [英] Kotlin Android View Binding: findViewById vs Butterknife vs Kotlin Android Extension
问题描述
我正在尝试找出在 Kotlin 中进行 Android 视图绑定的最佳方法.似乎有几个选项:
findViewById
val button: Button by lazy { findViewById
黄油刀
我的建议是:
- findViewById:老派.避免.
- ButterKnife:老派,但更少的样板和一些附加功能.仍然缺乏编译时安全性.尽可能避免.
- Kotlin Synthetic:真是一个优雅的 findViewbyId 缓存版本.更好的性能和更少的样板,但仍然没有编译时安全.如果不需要编译时安全,则是最佳选择.
- ViewBinding:介于选项 1-3 和数据绑定之间.但缺乏DataBinding 的强大选项(例如 2 路数据绑定和在 XML 文件中使用变量).
- 数据绑定:最强大的选项.与 LiveData 和 ViewModels (JetPack) 完美集成以创建反应式 UI(类似于 RxJava).可以减慢大型项目/用户界面的构建时间(使用注释处理器,就像 ButterKnife 一样).我的个人喜好.
另见:https://www.youtube.com/watch?v=Qxj2eBmXLHg一个>
有趣的是,Jake Wharton(ButterKnife 的原作者)现已加入 Google,并致力于 ViewBinding.
I'm trying to figure out the best way to do Android View Binding in Kotlin. It seems like there are a few of options out there:
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 Extensions
https://kotlinlang.org/docs/tutorials/android-plugin.html
import kotlinx.android.synthetic.main.activity_main.*
I'm pretty familiar with findViewById and Butterknife in java land, but what are the pros and cons of each view binding approach in Kotlin?
Does Kotlin Android Extensions play well with the RecyclerView + ViewHolder pattern?
Also how does Kotlin Android Extensions handle view binding for nested views via include
?
ex: For an Activity using activity_main.xml
, how would View custom1
be accessed?
activity_main.xml
<...>
<include layout="@layout/custom" android:id="@+id/custom" />
</>
custom.xml
<...>
<View android:id="@+id/custom1" ... />
<View android:id="@+id/custom2" ... />
</>
There are a lot of ways to access views in Android. A quick overview:
My advise would be:
- findViewById: old school. Avoid.
- ButterKnife: old school, but less boilerplate and some added functionality. Still lacks compile time safety. Avoid if possible.
- Kotlin Synthetic: really a elegant cached version of findViewbyId. Better performance and way less boilerplate but still no compile time safety. Best option if compile time safety is not needed.
- ViewBinding: Somewhere in between option 1-3 and Databinding. But lacks powerful options of DataBinding (like 2 way data binding and using variables inside XML files).
- Data Binding: most powerful option. Integrates really nice with LiveData and ViewModels (JetPack) to create reactive UI's (similar to RxJava). Can slow down build times (uses annotation processor just like ButterKnife) on large projects/UI's. My personal preference.
See also: https://www.youtube.com/watch?v=Qxj2eBmXLHg
Funny to note that Jake Wharton (original author of ButterKnife) has now joined Google and works on ViewBinding.
这篇关于Kotlin Android 视图绑定:findViewById 与 Butterknife 与 Kotlin Android 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!