0x01 ViewBinding
1.使用 View Binding 先要在Module 的 build.gradle
文件注册
1 | android { |
2.会根据布局文件,编译之后自动生成对应的Binding class,可以在Activity 和 Fragment 直接调用 inflate 使用
1 | private var _binding: ResultProfileBinding? = null |
0x02 DataBinding
1.在 build.gradle
文件中开启lib
1 | android { |
2.布局文件start with a root tag of layout
followed by a data
element
1 | <layout xmlns:android="http://schemas.android.com/apk/res/android" |
3.在Activity中使用
1 | override fun onCreate(savedInstanceState: Bundle?) { |
在 Fragment
, ListView
, or RecyclerView
adapter, you may prefer to use the inflate()
1 | val listItemBinding = ListItemBinding.inflate(layoutInflater, viewGroup, false) |
0x03 view binding 和 data binding 比较
View binding and data binding both generate binding classes that you can use to reference views directly. However, view binding is intended to handle simpler use cases and provides the following benefits over data binding:
- Faster compilation: View binding requires no annotation processing, so compile times are faster.
- Ease of use: View binding does not require specially-tagged XML layout files, so it is faster to adopt in your apps. Once you enable view binding in a module, it applies to all of that module’s layouts automatically.
Conversely, view binding has the following limitations compared to data binding:
- View binding doesn’t support layout variables or layout expressions, so it can’t be used to declare dynamic UI content straight from XML layout files.
- View binding doesn’t support two-way data binding.
Because of these considerations, it is best in some cases to use both view binding and data binding in a project. You can use data binding in layouts that require advanced features and use view binding in layouts that do not.
0x04 遇到的坑
等标签,如果使用databinding ,子布局xml的 root tag 依旧需要layout 标签嵌套 data 标签。否者编译报错,找不到对应的属性