DataBinding is intended to replace the findViewById() method, but it does more than that.

configuration

  1. inbuild.gradleOpen function in
android {
    ...
    dataBinding {
        enabled = true}}Copy the code
  1. ingradle.propertiesEnables the new compiler in
android.databinding.enableV2=true
Copy the code

Basic operation

Implementing a Databinding is basically a three-step process

1. Create a data source

That is, plain JavaBean objects.

2. Define in XML

Databinding supports layout files with fixed < Layout > tags and requires a tag to declare the data source.

<? xml version="1.0" encoding="utf-8"? > <layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="user" type="com.example.User"/> </data> <LinearLayout <-- Layout file! --> </LinearLayout> </layout>Copy the code

In the above XML file, the

tag declares a variable that is available in XML, and the two properties in it correspond to the variable name and the variable type.

With the data source variable, we can bind it to the specified control:

<TextView 
	android:id="@+id/name"
	android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@{user.firstName}" />
Copy the code

3. Use it in an activity

According to the Android developer documentation, when you create a databinding layout file, the Gradle compiler automatically generates a bound class for it.

The Binding class is named camel XML file name + binding.java.

Get it in the activity as follows:

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
Copy the code

Once you have a Binding object you can use the controls in the layout file directly:

/ / control variable name is layout file id of the binding. The name, setBackgroundColor (Color. WHITE);Copy the code

Of course we don’t need to manually assign to each space, just:

User user = new User("Test"."User");
binding.setUser(user);
Copy the code

Click on the event

There are two ways to listen to click events:

  1. Call the method directly. This is similar to setting onclick in the activity before, the registration method must beonClick(View view)Of the form, which takes a View parameter, can be used as follows:
android:onClick="@{objectName::funName}"
Copy the code
  1. Bind listeners. This method has no requirements for the registered method, there are no parameters, parameter type is not limited, the use of the method is:
android:onClick="@{() -> presenter.onSaveClick(task)}"
Copy the code

This is a lamda expression, and the view argument in the parentheses is optional. It registers a listener.

The second method is obviously more flexible, not only passing any parameters as needed, but also not forcing the registration method to pass view parameters.

RecyclerView used in

Implement in Adapter:

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
    Test test = data.get(i);
    viewHolder.itemListBinding.setVariable(BR.test,test); } class ViewHolder extends RecyclerView.ViewHolder { private ItemListBinding itemListBinding; ViewHolder(@NonNull View itemView) { super(itemView); itemListBinding = DataBindingUtil.bind(itemView); }}Copy the code

BR is an automatically generated class that contains all the variable ids under the Layout tag.

Binding adapter

In addition to the standard text data during development, there are more special data, such as loading an image from the network can not be directly bound in XML, which is where the binding adapter is needed. Customizing a binding adapter is simple:

public class ImageUtil {

    @BindingAdapter({"imageUrl"}) public static void showImage(ImageView ImageView, String URL) {// Annotated methods must be static. Glide.with(imageView.getContext()).load(url).into(imageView); }}Copy the code

Then use it directly in XML:

<ImageView app:imageUrl="@{user.imageUrl}" />
Copy the code

Brief Introduction of implementation Principle

DataBinding doesn’t actually replace findViewById(). Instead, it encapsulates findViewById(). The Android plugin automatically converts the layout of the root tag < Layout > into the corresponding bound class.