Lets start a professional way in android app development by using Data Binding in Android Studio. Furthermore, data binding library enables you to bind the UI components in the layout files to the app data sources. Moreover, it lets you to remove many UI framework calls in your activity. So that, it improve your app’s performance and help prevent memory leaks and null pointer exceptions. When data binding is enabled it generates binding class that takes the name name of the XML layout files with camel case and adding the “Binding” word. But, it differ from the view binding in the following:
- It support layout variable and layout expressions. So, it enables you to declare the dynamic UI components directly from XML layout files.
- It supports two-way data binding.
How to setup Data Binding in Android Studio?
In order to setup and use Data Binding you need first to update the latest android plugin for gradle and also to use updated IDE and SDK tools.
To setup your app to use data binding in android studio, enable the data binding build option in your file in the app module gradle file, as shown in the following example.
android {
buildFeatures {
dataBinding true
}
}
When Data Binding enabled the binding class for each XML layout file generated. Moreover, the name of binding class created by converting the nname of XML layout file Camel case and adding the word “Binding” to the end. For example:
- activity_main.xml file: will generate “ActivityMainBindig” class.
- activity_startup.xml file: will generate “ActivityStartupBinding” class.
- activity_user.xml file: will generate “ActivityUserBinding” class.
Layouts and binding expressions
The expression language allows you to write expressions that handle event dispatched by view. Furthermore, data binding layout files are slightly different. As, it starts with root tag “layout” and followed by “data” element and “view” element. see the following example for setting up data binding for main activity xml layout file. Note that I have created a new Java class for User data.
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="user" type="com.androidhands.databindingdemo.User"/> </data> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textName" android:text="@{user.name}"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textAge" android:text="@{user.age}"/> </LinearLayout> </layout>
User model class as following:
public class User {
String name;
String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
There are two ways for binding data in main activity. The first is using DataBindingUtil as following:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding activityMainBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
User user = new User("Android Hands","1 Year");
activityMainBinding.setUser(user);
}
}
You also can use the generated binding class ActivityMainBinding.
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding activityMainBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(activityMainBinding.getRoot());
User user = new User("Android Hands","1 Year");
activityMainBinding.setUser(user);
}
}
Expression language
The expression language looks a lot like expressions found in managed code. Moreover, you can use the following operators and keywords in the expression language:
- Mathematical
+ - / * %
- String concatenation
+
- Logical
&& ||
- Binary
& | ^
- Unary
+ - ! ~
- Shift
>> >>> <<
- Comparison
== > < >= <=
(Note that<
needs to be escaped as<
) instanceof
- Grouping
()
- Literals – character, String, numeric,
null
- Cast
- Method calls
- Field access
- Array access
[]
- Ternary operator
?:
For example:
android:text="@{String.valueOf(index + 1)}"
android:visibility="@{age > 13 ? View.GONE : View.VISIBLE}"
android:transitionName='@{"image_" + id}'
Null coalescing operator
The null coalescing operator (??
) chooses the left operand if it isn’t null
or the right if the former is null
.
android:text="@{user.displayName ?? user.lastName}" This is functionally equivalent to: android:text="@{user.displayName != null ? user.displayName : user.lastName}"
Using Collections in Data Binding
Finally, you can use collection as lists, arrays, sparse lists and maps in data binding. Moreover, you can access it using the []
operator for convenience.
<data> <import type="android.util.SparseArray"/> <import type="java.util.Map"/> <import type="java.util.List"/> <variable name="list" type="List<String>"/> <variable name="sparse" type="SparseArray<String>"/> <variable name="map" type="Map<String, String>"/> <variable name="index" type="int"/> <variable name="key" type="String"/> </data> … android:text="@{list[index]}" … android:text="@{sparse[index]}" … android:text="@{map[key]}"
Note: For the XML to be syntactically correct, you have to escape the<
characters. For example: instead ofList<String>
you have to writeList<String>
.