当前位置:网站首页>It should be so simple. Databinding and viewbinding
It should be so simple. Databinding and viewbinding
2022-07-18 02:32:00 【hi-dhl】

Preface
First of all, I wish my friends a happy new year ,2020 An extraordinary year ,2021 It's a new starting point for you and me .
2021 New signature : Code is more than , The article keeps on .
2021 The first article is right 2020 The last article at the end of the year Kotlin The end of the plug-in ,ViewBinding The rise of A supplement to .
Previous articles Kotlin The end of the plug-in ,ViewBinding The rise of This paper introduces the in Google Why is it not recommended to use Kotlin Synthesis method (Synthetic View ), Google It is recommended to use ViewBinding Replace Kotlin Synthesis method , that ViewBinding and DataBinding What's the difference .
ViewBinding:
- Only binding is supported View
- There is no need to add... To the layout file layout label
- At the module level
build.gradleAdd... To the fileviewBinding = trueYou can use - Efficiency is higher than DataBinding, Because it avoids the overhead and performance problems associated with data binding
- Compared with
kotlin-android-extensionsThe plug-in avoids null exceptions
DataBinding:
- Contains ViewBinding All functions
- At the module level
build.gradleAdd in filedataBinding = trueAnd you need to add... In the layout file layout Tags can be used - Support data and view Two way binding
- Less efficient than ViewBinding, Because the annotation processor will affect the construction time of data binding .
ViewBinding It can be realized , DataBinding Can be realized , however DataBinding The performance of the system is lower than that of the system ViewBinding,DataBinding and ViewBinding For every one of them XML File generation binding class .
R.layout.activity_main -> ActivityMainBinding
R.layout.fragment_main -> FragmentMainBinding
R.layout.dialog_app -> DialogAppBinding
stay Kotlin The end of the plug-in ,ViewBinding The rise of The article also analyzes Kotlin Problems caused by synthetic methods . Even if Kotlin There are many problems with the synthesis method , But there are still friends willing to use .
ViewBinding and DataBinding Solved so many problems for us , But why are many friends unwilling to use ViewBinding and DataBinding, Today we will analyze it from the perspective of use .
ViewBinding and DataBinding
I probably summarized ViewBinding and DataBinding All uses in different scenarios , Let's take a look at how to use .
Basic configuration
from Android Studio 3.6 Version start , Built in Gradle Plug in , There is no need to add any additional libraries to use them , But in Android Studio 3.6 and Android Studio 4.0 It is used in different ways .
// Android Studio 3.6
android {
viewBinding {
enabled = true
}
dataBinding{
enabled = true
}
}
// Android Studio 4.0
android {
buildFeatures {
dataBinding = true
viewBinding = true
}
}
ViewBinding Use
Because there are many scenes involved , In order to reduce the space , I only list the core parts , If you have never used it before , All we need to know here is ViewBinding The threshold ratio of Kotlin The synthesis method should be high .
Do not want to generate for a layout binding class , Add the following attributes to the root view of the layout file
<LinearLayout tools:viewBindingIgnore="true" >
</LinearLayout>
stay Activity Use in
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
stay Fragment Use in
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val binding = FragmentViewBindBinding.inflate(inflater,container,false)
return binding.root
}
stay Adapter The use of
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
RecycleItemProductBinding.inflate(LayoutInflater.from(parent.context), parent, false)
}
stay Dialog Use in
override fun onCreate(savedInstanceState: Bundle?) {
binding = DialogAppBinding.inflate(layoutInflater)
setContentView(binding.root)
}
include Use of labels
include Without label merge label , Need to give include add id, Use it directly id that will do , Use as follows .
<include
android:id="@+id/include"
layout="@layout/layout_include_item" />
val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
binding.include.includeTvTitle.setText(" Use include Control in layout , It doesn't contain merge")
include Label tape merge label , Notice here and DataBinding The usage is different , to include add id, stay DataBinding Can be used directly in id,ViewBinding No way. ,ViewBinding The usage of is as follows .
<include layout="@layout/layout_merge_item" />
val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
val mergeItemBinding = LayoutMergeItemBinding.bind(binding.root)
mergeItemBinding.mergeTvTitle.setText(" Use include Control in layout , contain merge")
ViewStub Use of labels
According to practice , As of the publication of this article , stay Android Studio 4.2.0 bata 2 in , Can't be directly in ViewBinding Use... In layout ViewStub label , Only in DataBinding Layout ( belt layout label ) Use in , See issue
Because there is no authoritative data to prove , Here, I suggest you to work directly on the project Binding Try to , If there are others ViewBinding Implementation method in layout , Please leave me a message
DataBinding Use
Because there are many scenes involved , In order to reduce the space , I only list the core parts , If you have never used it before , All we need to know here is DataBinding The threshold ratio of Kotlin The synthesis method should be high .
You need to add layout label
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout...>
...
</LinearLayout
</layout>
stay Activity Use in
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
setContentView(binding.root)
}
stay Fragment Use in
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val binding = FragmentViewBindBinding.inflate(inflater,container,false)
binding.lifecycleOwner = this
return binding.root
}
stay Adapter The use of
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(viewType, parent, false)
val bidning:RecycleItemProductBinding = DataBindingUtil.bind(view)
}
stay Dialog Use in
override fun onCreate(savedInstanceState: Bundle?) {
binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_data_binding, null, false)
setContentView(binding.root)
}
include Use of labels
include Without label merge label , Need to give include add id, Use it directly id that will do .
<include
android:id="@+id/includeData"
layout="@layout/layout_include_data_item"/>
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.includeData.includeTvTitle.setText(" Set by code include layout Control for ")
include Label tape merge label , Notice here and ViewBinding The usage is different , to include add id, stay DataBinding Can be used directly in , stay ViewBinding But not in the middle .
<include
android:id="@+id/includeDataMerge"
layout="@layout/layout_merge_data_item"/>
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.includeDataMerge.mergeTvTitle.setText(" Set by code merge layout Control for ")
ViewStub Use of labels
to ViewStub add id, stay DataBinding Can be used directly in id that will do .
<ViewStub
android:id="@+id/stub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/view_stub" />
binding.stub.setOnInflateListener { stub, inflated ->
// ViewBinding
val viewStub: ViewStubBinding = ViewStubBinding.bind(inflated)
viewStub.tvTitle.setText(" Use ViewStub load ViewBinding Layout ")
}
binding.stub.setOnInflateListener { stub, inflated ->
// DataBinding
val dataViewStub: ViewStubDataBinding = DataBindingUtil.bind(inflated)!!
dataViewStub.tvTitle.setText(" Use ViewStub load DataBinding Layout ")
}
if (!binding.stub.isInflated) {
binding.stub.viewStub!!.inflate()
}
As you can see , stay Ativity 、 Fragment 、 Dialog 、 Adapter 、 include 、 merge 、 ViewStub And so on , Use ViewBinding perhaps DataBinding Have to be handled differently , Compared with Kotlin Synthesis method , The threshold is too high .
So can you use a method , These initialization schemes can be unified , stay Kotlin You only need one line of code to realize DataBinding and ViewBinding.
One line of code
If you need to do different processing manually in each scene , This cost is very large , So I launched a new library Binding ,Binding combination Kotlin Delegate properties , Unified package DataBinding and ViewBinding Different treatments , Simple is provided API As shown below .
ViewBinding The use of
val binding: ActivityViewBindBinding by viewbind()
DataBinding The use of
val binding: ActivityDataBindBinding by databind(R.layout.activity_data_bind)
perhaps
val binding: ActivityDataBindBinding by databind()
As you can see , Just a few simple API All the above scenarios can be realized , Let's introduce Binding.
Binding Future planning provides a common findViewById Solution , Due to the iterative update of technology, from butterknife 、 DataBinding 、 Kotlin Synthesis method (Synthetic View ) Up to now ViewBinding , There may also be new technologies in the future , No matter how the technology changes , as long as Binding External use remains unchanged , Just update Binding , You can complete the migration .
Binding Has the following advantages :
- Many practical cases are provided, including
Ativity、Fragment、Dialog、Adapter、include、merge、ViewStub、Navigation、 Data bidirectional binding Scenes, etc. - ordinary API It takes only one line of code to achieve DataBinding perhaps ViewBinding
- Support in
Activity、AppCompatActivity、FragmentActivity、Fragment、DialogThe use of DataBinding perhaps ViewBinding - Support in
ListAdapter、PagedListAdapter、PagingDataAdapter、RecyclerView.AdapterThe use of DataBinding perhaps ViewBinding - Support in Navigaion Fragment Management framework 、 BottomSheetDialogFragment And so on DataBinding and ViewBinding
- Avoid a lot of template code
- Avoid memory leaks , Life cycle awareness , When the life cycle is in
onDestroyed()The data will be automatically destroyed
Next, let's analyze how to use Binding, Add the following code at the module level build.gradle In the file , And it needs to be turned on DataBinding perhaps ViewBinding.
dependencies {
implementation 'com.hi-dhl:binding:1.0.7'
}
stay Activity 、AppCompatActivity 、FragmentActivity Use in , add to by viewbind() perhaps by databind(R.layout.activity_main) that will do , An example is shown below .
class MainActivity : AppCompatActivity() {
// DataBinding
val binding: ActivityMainBinding by databind(R.layout.activity_main)
// ViewBinding
val binding: ActivityMainBinding by viewbind()
}
stay Fragment There are two ways :
- Mode one : stay
onCreateViewUse in , This method applies to all usesFragmentScene - Mode two : stay
onViewCreatedUse in
Mode one :
class FragmentNav1 : Fragment(R.layout.fragment_main) {
// DataBinding
val binding: FragmentMainBinding by databind()
// ViewBinding
val binding: FragmentMainBinding by viewbind()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return binding.root
}
}
Mode two , The following points need to be noted :
- Can't be in
Navigaion FragmentandBottomSheetDialogFragmentUse in - Among others Fragment Scene , If you use
Mode twoThe interface does not display , change to the use of sth.Mode oneCan solve
class FragmentNav1 : Fragment(R.layout.fragment_main) {
// DataBinding
val binding: FragmentMainBinding by databind()
// ViewBinding
val binding: FragmentMainBinding by viewbind()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply { textView.setText("Binding") }
}
}
stay Dialog The method of use in is as follows .
class AppDialog(context: Context) : Dialog(context, R.style.AppDialog) {
// DataBinding
val binding: DialogAppBinding by databind(R.layout.dialog_data_binding)
// ViewBinding
val binding: DialogAppBinding by viewbind()
}
Or add life cycle aware Dialog.
class AppDialog(context: Context,lifecycle: Lifecycle) : Dialog(context, R.style.AppDialog) {
// DataBinding Monitor life cycle
val binding: DialogAppBinding by databind(R.layout.dialog_data_binding, lifecycle)
// ViewBinding Monitor life cycle
val binding: DialogAppBinding by viewbind(lifecycle)
}
stay Adapter Use in DataBinding and ViewBinding, Only need ViewHolder Add by viewbind() perhaps by databind() that will do , An example is shown below .
class ProductViewHolder(view: View) : RecyclerView.ViewHolder(view) {
// DataBinding
val binding: RecycleItemProductBinding by databind()
// ViewBinding
val binding: RecycleItemProductHeaderBinding by viewbind()
}
Extension method , Support DataBinding Bind data during initialization .
val binding: ActivityDataBindBinding by databind(R.layout.activity_data_bind) {
val account = Account()
account.name = "test"
this.account = account
}
The above is just a few common usages , Of course, there are more practical cases (include 、 merge 、 ViewStub 、 Navigation 、 Data bidirectional binding wait ) It has been uploaded to GitHub Welcome to the warehouse Binding see .
GitHub Warehouse : https://github.com/hi-dhl/Binding
This article can be understood as a review of the previous article Kotlin The end of the plug-in ,ViewBinding The rise of A supplement to , From the perspective of use DataBinding and ViewBinding The difference , At the same time, it also introduces how to realize in a simpler way DataBinding and ViewBinding.
This is the end of the article , If it helps Point a praise Is the biggest encouragement to me
Code is more than , The article keeps on
Keep sharing the latest technology
Finally, I recommend the projects and websites that I have been updating and maintaining :
A new series of videos : modern Android Development (MAD) Tips series : Check online
Plan to build the most complete 、 Abreast of the times AndroidX Jetpack The actual combat projects of related components as well as Related component principle analysis article , It's increasing Jetpack New blood , The warehouse is constantly updated , Welcome to check :AndroidX-Jetpack-Practice
LeetCode / The finger of the sword offer / Interview questions of big factories at home and abroad / Multithreading Answer key , Language Java and kotlin, There are many solutions 、 Their thinking 、 Time complexity 、 Spatial complexity analysis

- The finger of the sword offer And domestic and foreign big factory interview question solution : Read online
- LeetCode A series of questions : Read online
newest Android 10 Source code analysis series , Understand the source code of the system , It's not only helpful to analyze problems , During the interview , It's also very helpful to us , The warehouse is constantly updated , Welcome to check Android10-Source-Analysis
Organize and translate a series of selected foreign technical articles , There will be one in every article Reflections on Translators part , A deeper understanding of the original text , The warehouse is constantly updated , Welcome to check Technical-Article-Translation
「 Designed for Internet people , Domestic and foreign famous station navigation 」 Including news 、 sports 、 life 、 entertainment 、 Design 、 product 、 operating 、 The front-end development 、Android Development and so on , Welcome to check Design navigation website for Internet people
边栏推荐
- 2022-04-20 Unity入门9——其他
- [flag] build a website around Li Jian that sorts and classifies by time axis and content (zero basis) (continuous update)
- Latex數學公式
- 2022-04-18 introduction to unity 2 - how unity works
- Twitter vs musk: it's not that easy to leave
- Use iceberg in CDP to pressurize the data Lake warehouse
- 2022-04-21 Unity入门8——音效系统
- Open source real-time data warehouse Apache Doris graduated, how to go further in the future?
- 05 USART发送和接收数据(查询模式)
- QT connection MySQL
猜你喜欢

许式伟:Go+ 演进之路

【毕设选题】基于STM32的毕业设计题目项目汇总 - 350例

Single vehicle management system - 1 Document design and SQL code description

Latex数学公式

PowerDesigner安装教程

竟然如此简单,DataBinding 和 ViewBinding

抖音推出“团购配送”,探索外卖新模式

Learn FPGA from the bottom structure --- MMCM and PLL

Configure the C locale of sublime

在 CDP中使用Iceberg 为数据湖仓增压
随机推荐
[hero planet July training leetcode problem solving daily] 15th binary tree
如何复活古人?#MetaHuman 让万年前的骨架重获肉身
BC20 AT指令测试
神奇宝贝 眼前一亮的 Jetpack + MVVM 极简实战
Career masters help you with interview and job search + career development
2022-04-18 unity getting started 3 - script Basics
MySQL神器之一锁
A---DMA串口通信
Fragment(三)ViewPager中使用Fragment
PowerDesigner安装教程
Svn download and Chinese package installation
云呐-动环监控系统的主要功能是什么
Beijing Institute of technology - spring 2021 - Digital Logic Experiment
Kotlin StateFlow 搜索功能的实践 DB + NetWork
Is there a future for the Internet?
How to encapsulate kotlin + Android databinding in a project
牛文文:专精特新时代,需要新样板、新风貌
Experiment 2 Data modeling of after sales service management system
Kotlin 插件的落幕,ViewBinding 的崛起
03 按键控制LED