ViewBinding and DataBinding of Android Jetpack

ViewBinding and DataBinding of Android Jetpack Introduction

ViewBinding and DataBinding of Android Jetpack

foreword
Jetpack is a set of libraries, tools, and guides that make it easier for developers to write high-quality apps.
No matter where you go now, if Android developers say they don’t know Jetpack, they will be looked at with “ contempt”. Starting today, I will write a series of articles on Jetpack, let’s learn the powerful Jetpack together .

ViewBinding and DataBinding of Android Jetpack.ViewBinding


Through view binding, the system will generate a binding class for each XML layout file in the module. Through the binding class, we can directly manipulate the control id without findingViewById , so that we can avoid null pointers where the control id is invalid. question.
First, we create a new project, create a new MainActivity , the corresponding layout file is named: activity_main , and enable view binding in the module's build.gradle :
viewBinding {
enabled = true
}

After compiling, the system will automatically generate the name ActivityMainBinding , we add a text box and a button in activity_main.xml
< EditText
android:id="@+id/ed_input"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout _height =" wrap_content "
android:text ="save" />

Next, modify the code in MainActivity
@Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate ( savedInstanceState );
ActivityMainBinding activityMainBinding = ActivityMainBinding.inflate ( LayoutInflater.from (this));
setContentView ( activityMainBinding.getRoot ());
}

Next, we can directly use the control corresponding to the id
activityMainBinding.btnSave.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick ( View v) {
String content = activityMainBinding.edInput.getText (). toString ();
Toast.makeText ( MainActivity.this , content, Toast.LENGTH_SHORT ).show ();
}
});

The running result is shown in the figure

ViewBinding is just to replace findViewById , the advantage is empty safety, but with kotlin -android -extensions, ViewBinding should be used less.
DataBinding
The simple explanation of data binding is that before, we needed to set data through the control by getting the control. Now with data binding, we can directly bind the data directly in the layout file.
as ViewBinging , we first configure it in build.gradle
dataBinding {
enabled = true
}

Create a new Main2Activity, the corresponding layout is as follows:
xmlns:tools ="http://schemas.android.com/tools"
android: layout_width =" match_parent "
android:layout _height =" match_parent "
tools:context =".Main2Activity">


The root layout of the xml file using data binding must be the layout tag. We create a new User class with name and gender fields
public class User {
....
private String userName ;
private String userGender ;
....
}

First import the data to be bound through the data tag

name="user"
type=" com.example.jetpackdemo.bean.User " / >


We add two textViews to the xml to display the user's name and gender
< LinearLayout
android: layout_width =" match_parent "
android:layout _height =" wrap_content "
android:orientation="vertical">

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.userName}"
android:textSize="17sp" />
android: layout_width =" match_parent "
android:layout _height =" wrap_content "
android:text ="@{ user.userGender }"
android:textSize ="17sp" />


Set data by reference to @{}
Set the data source in Main2Activity by the following method:
ActivityMain2Binding activityMain2Binding = DataBindingUtil.setContentView (this, R.layout .activity_main2);
User user = new User("Huang Linqing", "Male");
activityMain2Binding.setUser(user);

Running the program looks like this:
If we change the gender to null now, the gender will not be displayed directly

What if we now ask to display "not set" when the gender is null, we can judge in xml
TextUtil under the data tag


< TextView
android: layout_width =" match_parent "
android:layout _height =" wrap_content "
android:text ='@{ TextUtils.isEmpty ( user.userGender )? "Not set": user.userGender }'
android:textSize ="17sp" />

The running result is shown in the figure below

In addition to data binding, there are also monitoring event bindings, etc., so I will not give examples in detail. What we are currently doing is static data binding. Many times we need dynamic binding, so how to automatically update when the data changes?

Using observable data objects
•observable field
Observable data type types are as follows:

Using observable data objects
•observable field
Observable data type types are as follows:


Next we add a button to reset the data in the user in the button
btnChanged = findViewById ( R.id.btn_change );
btnChanged.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick ( View v) {
user.userName.set ("Huang Linqing-changed value");
}
});


In this way, when the data changes, the data on our control can also change.
•observable collection
collections are often used in dynamic data structures. Using ObservableArrayMap to access key values is similar to data access in HashMap, which will not be introduced here.
•observable
observable data fields and collections, our favorite should be observable objects, so that we do not need to be limited by the original method of accessing data
public class User extends BaseObservable {
private String userName ;
private String userGender ;
public User(String userName, String userGender) {
this.userName = userName;
this.userGender = userGender;
}
@Bindable
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
notifyPropertyChanged(BR.userName);
}
@Bindable
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender;
notifyPropertyChanged ( BR.userGender );
}
}

We let the User class inherit from BaseObservable , use the Bindable annotation to register notifications, and send notifications through notifyPropertyChanged () when the value changes. The BR class is a class for the ID of the data-binding resource generated for data binding. In Main2Activity the same set the initial value, click the button to change the value
ActivityMain2Binding activityMain2Binding = DataBindingUtil.setContentView (this, R.layout .activity_main2);
User user = new User("Huang Linqing-Variable Object", "Male");
activityMain2Binding.setUser(user);
btnChanged = findViewById ( R.id.btn_change );
btnChanged.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick ( View v) {
user.setUserName ("Huang Linqing-Data Update");
}
});

ViewBinding and DataBinding of Android Jetpack.After running, click the button and the result is as follows:



Android Studio 3.1 and higher versions allow to replace observable fields with LiveData objects. Combined with the use of JetPack, LiveData is recommended for data notifications. We will use this example again when we talk about LiveData .
DataBinding and ViewBinding are here, we can already use the basic functions, and we need more practice in the project development.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00