1. Gradle configuration
  2. The XML configuration
  3. Bloat View

DataBinding is a library for Jetpack that extends the capabilities of XML layout files and brings XML closer to activities/fragments. Further simplify development. Let’s introduce DataBinding.

Gradle configuration

We have to have it before we can use it. First we need to add the corresponding configuration in the build.gradle file of the module that needs to use the library:

apply plugin: 'kotlin-kapt'// Add annotations when needed

android {
   //code...
    dataBinding {
        enabled true / / enable dataBinding
    }
	// databinding. enabled = true
	//code...
}
Copy the code

After synchronization, you can use DataBinding.

2. XML configuration

XML configuration is the first step in using DataBinding. Our usual layout file looks like this

<androidx.constraintlayout.widget.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"><! - code - ></androidx.constraintlayout.widget.ConstraintLayout>
Copy the code

If you want the XML to use Databinding, you need to modify it:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class="MainLayoutBinding"><! -- There is a class attribute -- ><import type="android.text.Html" alias="html"/>
    <variable
        name="demo"
        type="String" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"><! - code - ></androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Copy the code

You can compare these two pieces of XML code, and what is left is the DataBinding configuration, which we will examine bit by bit.

2.1,<layout>The label

This tag is required, and only the layout wrapped with this tag will be recognized by Databinding, so < Layout > is the root tag of the layout file. Under this tag there are only two tags, one of which is , and the other is the original top-level tag of the layout file. Any layout file recognized by DataBinding automatically generates aBinding class whose name is converted from the layout file name — underline syntax to camel syntax +Binding: activity_main. XML results in the Binding class ActivityMainBinding

2.2,<data>The label

As the name indicates, the tag is used by DataBinding to provide data in the XML. You can see that the tag has a class attribute, which provides the name for the automatically generated binding class. That is, activity_main.xml will get the binding class MainLayoutBinding

It is recommended to follow the original syntax when customizing the Binding class name: add Binding at the end to indicate that it is a layout Binding class.

There can be two tags under this tag:

and

.


: Import tags that can be imported for specific classes and then used in XML in the DataBinding environment. Type is the full class name of the class to be imported, and alias is the alias. (You can use

to be equivalent to Java/Kotlin’s imort keyword.) Usage: Mainly used to import classes and use static methods


: A variable tag that makes it possible to use data objects directly in XML through binding expressions by calling the corresponding method in Java/Kotlin code to pass in a specific object. Name is the name of the variable and type is the type of the variable.

At this point, the dataBinding configuration in XML is almost complete.

2.3. Bind expressions

To use Databinding in XML:@ {/ / code... }Here’s an example:

2.4. Use shortcut keys for quick configuration

You can place the cursor over the root TAB in the XML layout and use the shortcut key Option + Enter to call the following screen:

Selecting the first option completes the XML configuration of the dataBinding. This shortcut corresponds to:

You can find and change it yourself in the KeyMap configuration of Android Studio.

3. Inflate view

With a normal layout XML View, you can inflate the XML into a View so that the layout can be accessed in your code environment through methods like view.inflate (), layoutinflater.from (this).inflate(), and so on. DataBinding also provides us with a set of methods, provided by DataBindingUtil, and the inflate principle is the same as before:

val binding = DataBindingUtil.inflate<ActivityMainBinding>(
    layoutInflater,
    R.layout.activity_main,
    parent,
    true
)
Copy the code

If you are setting the root view for an activity, you can do this:

override fun onCreate(savedInstanceState: Bundle?). {
    super.onCreate(savedInstanceState)
/ / code...
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
/ / code...
}
Copy the code

Another easy way to do this is to have a inflate through the static method of the binding class:

val binding = ActivityMainBinding.inflate(layoutInflater,parent,true)
Copy the code

Each of these methods results in an object binding for the corresponding binding class, from which we can directly access the information in the layout file through properties (immutable fields) that are generated based on the control ID in the layout file. The biggest benefit is getting rid of findViewById.

3.1. Combine LiveData

ViewDataBinding has a LifecycleOwner set so that you can bind LiveData directly in the binding expression without listening in the Activity/Fragment.

3.2. Use of bind

When you use the DataBindingUtil class, you’ll find a bind method that can retrieve the corresponding bound class through a view.

val binding = DataBindingUtil.inflate<ActivityMainBinding>(
/ / code...
) // Get a bound class
val root:View = binding.root // Get a root View
Val bind:ActivityMainBinding = DataBindingUtil.bind(root)// Get the bound class again from the root View
Copy the code

Imagine this scenario: you have an ActivityMainBinding class, but at some point you need to convert it to a View, such as a RecyclerView/ListView Adapter. You can get the View by binding the class’s getRoot method. At a later point, however, you find that you still need to bind the class to do some processing, so you can use the bind method to retrieve the corresponding bound class from the View (obtained from getRoot).

The advantage of this is that you don’t have to maintain the bound classes all the time, but they are always available when you need them.

3.3. Set variables

Remember the tag in XML? The

tag represents a variable that generates a pair of get and set methods in the binding class.

Binding. demo = "This is a variable"// Since it is Kotlin, we can get a variable
Copy the code

In addition to the above method, there is another method of setting:

Binding. SetVariable (br.demo, "This is a variable")Copy the code

This is because DataBinding generates the corresponding BR value based on the

tag in the
tag. SetVariable methods do not belong to a specific binding class, but to their parent class, ViewDataBinding. They both get the same result.

3.4. Set click listener

Yes, with dataBinding we almost never have to write the setOnClickListener method in our code. We can bind click events directly to XML through DataBinding. To illustrate, I’ll place the events I need to bind on the Activity:

  1. Prepare a method:
#Activity
fun onClick(view:View){
/ / code...
}
Copy the code
  1. Bind the activity to the DataBinding
<data class="MainLayoutBinding">
	  <import type="android.text.Html" alias="html"/>
    <variable
        name="activity"
        type=".. Activity" /><! -- The full class name of the activity -- ></data>The < LinearLayout... ><TextView 
	onClick="@ {view ->Activity. The onClick (view)} "/ > <! -- Bind click listener -- ></LinearLayout>

Copy the code

In fact, there are other ways to click on a listener binding:

<TextView 
	onClick="@ {activity. The onClick}" />
<TextView 
	onClick="@ {activity: : onClick}" /><! -- These two have the same effect as above -- >Copy the code

You can also omit the view if you don’t need it:

<TextView 
	onClick="@ {()>Activity. The onClick ()} "/ >Copy the code

The same goes for binding other listeners. As you can see, there are no special restrictions on the methods that can be bound, so clicking on the event binding can be bound to almost any method.

summary

Databinding is a library for manipulating XML layouts. You can bind expressions to move operations that are part of a View from an Activity/Fragment to an XML layout file, reducing the Activity/Fragment burden. The ability to bind data directly, and even events directly, makes views less and less likely to appear in activities/fragments. Of course, this is only the first and simplest article in the Databinding series. The next article will cover the use of Databinding in XML, the various ways you can use String in XML, the resources hidden in XML, and the BindingAdapter.