dataBinding?

A : How to use Databinding?

B: such as read this circle.

Open setting

First , open your file which is in app/build.gradle , and you can see the android’ field , you need to write the code like this to open the dataBinding’ Setting.

1
2
3
4
5
6
android {
...
dataBinding {
enabled = true
}
}

Create a bean

Second , create a bean which is named User in your package , and create two variable as well as generate their constroctor. Two variable , name and age , were String variable and int variable . you must use the public to decorate two variable ,otherwise it wiil catch the Exception such as like this :

1
Could not find accessor package.User.name

here are the full code

1
2
3
4
5
6
7
8
9
10

public class User {
public String name;
public String age;

public User(String name, String age) {
this.name = name;
this.age = age;
}
}

Modify the xml

Thrid , add the label to root in your xml . by the way ,you need to write the android nameSpace in the layout element. create the label which in the label . create the label to import the User class which created juts now . create the label next to the with two property which is called name and type. you can write the name which just like user, and type must be call User .

Now , you can give the text to TextView by Using anroid:text=”@{user.name}”

here are the full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"ja>

<data>
<import type="com.ppjun.android.databinding.User"/>

<variable
name="user"
type="User"/>

</data>


<RelativeLayout

android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
android:layout_below="@+id/toolbar"
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.name}"
/>

<TextView
android:id="@+id/age"
android:layout_below="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.age}"/>


</RelativeLayout>
</layout>

Connect to the data

Final , gradle sync to generate the AcrivityMainBingding .

In the MainActivity ‘onCreate method , create the AcrivityMainBingding binding by Using the method DataBindingUtil.setCotnentView(this,R.layout.activity_main);

new the User variable by it’s constroctor.

user binding.setUser(user); to binding the xml.

here are the full code:

1
2
3
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user = new User("ppjun", "23");
binding.setUser(user);

run the application you will see the TextView text like ppjun and 23.

Summary

  1. DataBinding is easy for us to set the text without findviewbyid.
  2. The next article will show you more things about DataBinding.

Thanks for your watching.
:)