preface

ByteCode, dedicated to share the latest technology original articles, involving Kotlin, Jetpack, translation, system source code, LeetCode/point Offer/multithreading/domestic and foreign large factory algorithm problems and so on a series of articles.

Most guys have recently been notified of the update to Kotlin 1.4.20, which has made a major update as shown below:

To sum up briefly, there are mainly the following points:

  • abandonedkotlin-android-extensionsCompile the plug-in
  • ParcelableRelated functions have been moved to the new pluginkotlin-parcelize

According to Google, the Kotlin-Android-Extensions extension will only remain for at least a year and will be removed in September 2021 or later

The kotlin-Android-Extensions provide the following two functions:

  • Kotlin Synthetic view is used insteadfindViewById, by introducingkotlinx.android.syntheticThe ability to use control ids directly is, I suspect, what attracted many developers to learn and try Kotlin in the first place
  • Manual implementationParcelizeIt was a hassle, so Kotlin offered it@ParcelizeAnnotations help you quickly implement Parcelize

In fact this is not what new news, as early as 2019, when Google is put forward in the project is not recommended to use kotlinx. Android. Synthetic, see this commit, part of the content as shown in the figure below:

By introducing kotlinx. Android. Synthetic can directly use the ID of the control, so why not recommend the use of convenient? The main problems are as follows:

  • It is replaced by the Kotlin Synthetic viewfindViewByIdThis is done by caching the ID globally, regardless of Layout. There is no invalid check for the ID
  • If the same ID is used or the ID is deleted in different Layout files, it will not prompt empty exceptions, which will increase the number of App crashes
  • Only Kotlin is supported
  • The default is throughHashMapCaching ids wastes space, although it can be passed at the module levelbuild.gradleIn-file adddefaultCacheImplementation = "SPARSE_ARRAY"To change the default implementation toSparseArray
  • .

So ViewBinding appears. ViewBinding solves all the above problems. Although ViewBinding is good, it also has its disadvantages.

  • ViewBinding compared tokotlinx.android.syntheticThe way of use is complicated
  • inActivityFragmentDialogAdapterViewBinding and DataBinding are initialized somewhat differently in
  • It needs to be handled separatelyincludemergeTAB layout, and no beltmergeLayout of tags and so on
  • Using DataBinding in conjunction with LiveData requires separate processing
  • .

Both ViewBinding and DataBinding are complicated to use, and I’ll show you a way to use ViewBinding and DataBinding in a moment with just one line of code, So what’s the difference between ViewBinding and DataBinding?

ViewBinding and DataBinding

ViewBinding:

  • Only binding views are supported
  • You do not need to add layout labels to the layout file
  • Needs to be at the module levelbuild.gradleAdd to fileviewBinding = trueYou can use
  • It is more efficient than DataBinding because it avoids the overhead and performance issues associated with DataBinding
  • Compared to thekotlin-android-extensionsThe plug-in avoids null exceptions

DataBinding:

  • Contains all the functionality of ViewBinding
  • Needs to be at the module levelbuild.gradleIn-file adddataBinding = trueYou need to add the Layout label to the layout file to use it
  • Support data and view bidirectional binding
  • It is less efficient than ViewBinding because the annotation handler affects the build time of the data binding.

ViewBinding can be implemented, DataBinding can be implemented, but DataBinding is less performance than ViewBinding. DataBinding and ViewBinding generate bound classes for each XML file.

R.layout.activity_main -> ActivityMainBinding
R.layout.fragment_main -> FragmentMainBinding
R.layout.dialog_app -> DialogAppBinding
Copy the code

Gradle plug-ins have been built in since Android Studio 3.6. You don’t need to add any additional libraries to use them, but they are used differently in Android Studio 3.6 and Android Studio 4.0.

// Android Studio 3.6 Android {viewBinding {enabled = true} dataBinding{enabled = true}} // Android Studio 4.0 android { buildFeatures { dataBinding = true viewBinding = true } }Copy the code

Let’s take a look at how to use DataBinding and ViewBinding in a project. For reasons of length, this is only used in an Activity. For more examples, see the Binding library.

After starting DataBinding or ViewBinding in the build.gradle file at the module level, you need to initialize the Activity and use the ViewBinding instance.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Viewbinding
        val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
        
        // DataBinding
        // val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        
        with(binding){
            textView.setText("Binding")
        }
    }
}
Copy the code

If need to add in each Activity ActivityMainBinding. Inflate () or DataBindingUtil. The setContentView () method to initialize, it definitely add a lot of template code, It’s not just activities that need to be initialized in fragments, Dialogs, and Adapters.

So is there a way to unify these initializations that you can do in Kotlin with just one line of code for DataBinding and ViewBinding?

One line of code implements DataBinding and ViewBinding

If you need to manually add the same method to each Activity, Fragment, Dialog, or Adapter to initialize it, the cost is very high, so we combine the Kotlin delegate attribute to simplify the template code.

Binding simplifies the use of DataBinding and ViewBinding. It takes only one line of code to implement DataBinding and ViewBinding. They are implemented differently.

The future of Binding provides a general findViewById solution. As the technology iterates from Butterknife, DataBinding and Kotlin to ViewBinding, There may be new technologies in the future. No matter how technology changes, Binding only needs to be updated and external use remains unchanged. Let’s look at how to use the Binding library in your project.

  • Add the following code at the module levelbuild.gradleFile, and you need to enable DataBinding or ViewBinding
Dependencies {implementation 'com. Hi - DHL :binding:1.0.4}Copy the code
  • Use DataBinding and ViewBinding in Adapter (ListAdapter, PagingDataAdapter, RecyclerView.Adapter, etc.), addby viewbind()orby databind()An example is shown below.View detailed examples
Class ProductViewHolder(view: view) : recyclerViewholder (view) {// Use DataBinding to bind itemView val binding: RecycleItemProductBinding by databind() fun bindData(data: Product? , position: Int) { binding.apply { product = data executePendingBindings() } } } class ProductViewHolderHeader(view: View) : RecyclerView.ViewHolder(view) { // ViewBinding val binding: RecycleItemProductHeaderBinding by viewbind() fun bindData(data: Product? , position: Int) {binding. Apply {name. Text = "head bound by ViewBinding"}}}Copy the code
  • inActivityAppCompatActivityFragmentActivity, inherits the corresponding class additionby viewbind()Can be as follows.
class MainActivity : AppCompatActivity() {
    // DataBinding
    val binding: ActivityMainBinding by databind(R.layout.activity_main)
    // ViewBinding
    val binding: ActivityMainBinding by viewbind()
}
Copy the code
  • inFragmentThe usage mode is as follows.
class MainFragment : Fragment(R.layout.fragment_main) {
  	// DataBinding
  	val binding: FragmentMainBinding by databind()
    // ViewBinding
  	val binding: FragmentMainBinding by viewbind()
}
Copy the code
  • inDialogThe usage mode is as follows.
class AppDialog(context: Context) : Dialog(context, R.style.AppDialog) {
    val binding: DialogAppBinding by viewbind()
}
Copy the code

Add a life-cycle aware Dialog

class AppDialog(context: Context,lifecycle: Lifecycle) : Dialog(context, R.style.AppDialog) {
    val binding: DialogAppBinding by viewbind(lifecycle)
}
Copy the code

For more details, please visit the warehouse Binding. Binding has the following advantages:

  • Can be found inActivityAppCompatActivityFragmentActivityFragmentDialogListAdapterPagingDataAdapterRecyclerView.AdapterUse DataBinding or ViewBinding in
  • A simple API requires only one line of code to implement DataBinding or ViewBinding
  • Avoid lots of template code
  • Avoid memory leaks and have life cycle awareness when the life cycle is inonDestroyed()Will automatically destroy data

Source code analysis will be shared in subsequent articles, if this warehouse is helpful to you, please help me star in the upper right corner of the warehouse, thank you very much.

How to transferParcelable

Kotlin has moved Parcelable related functionality to a new plug-in, Kotlin-Parcelize, in two steps, as shown below.

  • In the module levelbuild.gradleIn the file, willkotlin-android-extensionsModified tokotlin-parcelize

  • willimport kotlinx.android.parcel.ParcelizeModified toimport kotlinx.parcelize.ParcelizeBut this step is not necessary,kotlinx.android.parcel.ParcelizeCan continue to use, so far no problems found (PS: if so, just replace the package name)

conclusion

The relevant code in this article has been uploaded to GitHub. Welcome to the repository Binding

Binding address: https://github.com/hi-dhl/Binding

Thanks for the Simple one-liner ViewBinding in Fragments and Activities with Kotlin’s article, And learn tips from open source libraries like Anko, ViewBindingDelegate, etc.

After a while, some friends asked me where I could read some foreign technical articles, so I also summarized some good websites for you.

Address: https://site.51git.cn/gonav/2

This is the end of the full text, if there is help to click a thumbs-up is the biggest encouragement to me!!

ByteCode, dedicated to share the latest technology original articles, involving Kotlin, Jetpack, translation, system source code, LeetCode/point Offer/multithreading/domestic and foreign large factory algorithm problems and so on a series of articles.


Finally, I recommend the projects and websites I have been updating and maintaining:

  • New video series: Modern Android Development (MAD) Tips series: View online

  • Androidx-jetpack-practice androidX-Jetpack-practice androidX-Jetpack-Practice androidX-Jetpack-Practice AndroidX-Jetpack-Practice

  • LeetCode/multiple thread solution, language Java and Kotlin, including a variety of solutions, problem solving ideas, time complexity, spatial complexity analysis

    • Job interview with major companies at home and abroad
    • LeetCode: Read online
  • Android10 Source code Analysis series of articles, understand the system Source code, not only help to analyze the problem, in the interview process, is also very helpful to us, the warehouse continues to update, welcome to check android10-source-Analysis

  • Collate and translate a series of selected foreign Technical articles, each Article will have a translator’s thinking part, a more in-depth interpretation of the original text, the warehouse continues to update, welcome to visit the Technical-Article-Translation

  • “Designed for Internet people, navigation of domestic and foreign famous stations” includes news, sports, life, entertainment, design, product, operation, front-end development, Android development and so on. Welcome to check the navigation website designed for Internet people

Article history

  • Kotlin’s Technique and Principle Analysis that few people know (1)
  • Kotlin’s Technique and Principle Analysis that few people know (II)
  • AndroidX App Startup practice and principle analysis of Jetpack’s latest member
  • Jetpack member Paging3 Practice and Source Code Analysis (PART 1)
  • Jetpack Member Paging3 Network Practice and Principle Analysis (II)
  • Jetpack member Paging3 retrieves network page data and updates it to the database
  • Jetpack member Hilt practice (1) Start a pit
  • Jetpack member Hilt with App Startup (ii) Advanced article
  • New member of Jetpack Hilt and Dagger are very different
  • All aspects of Hilt and Koin performance were analyzed
  • PokemonGo Jetpack + MVVM minimalism
  • What is Kotlin Sealed? Why does Google use them all
  • Kotlin StateFlow search features practice DB + NetWork
  • Bye-bye buildSrc, embrace Composing builds for faster Android builds
  • [Google] Bye SharedPreferences embrace Jetpack DataStore
  • Google is asking whether it should learn from Kotlin
  • An interesting new version of Android Studio has been announced