Linking UI layer with Data Model-Part -1
The Data Binding — Support library that facilitate you to bind layout’s UI components to data models directly in the layout itself rather than programmatically.
It means :
How does it help ?
1. Reduce boilerplate code in java files.
2. Increase readability in java files.
Disadvantages :
1. Creates additional autogenerated classes which is overhead on apk size.
2. Difficult to debug as code will be scattered in the java as well as xml file.
Steps to do data binding :
1.Add these lines in app build.gradle
// enable data binding for the application
android {
......
dataBinding {
enabled = true
}
}
2. Add layouts and binding expressions in the layout activity_main.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="user"
type="com.codehangouts.databindingdemo.User" />
</data>
<ConstraintLayout... /> <!-- UI layout's root element -->
</layout>
3. User the model reference in the layout xml wherever required.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content
android:text="@{user.name}" />
4. Binding data with Activity or Fragment
In case of Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//ActivityMainBinding will be autogenerated if activity_main
// is the layout name
ActivityMainBinding userBinding=DataBindingUtil. setContentView(this,R.layout.activity_main);
User user = …..// get or create the User object
....
....
userBinding.setUser(user);
}
In case of Fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
//FragmentDataBinding will be autogenerated if fragment_main
// is the layout name
FragmentMainBinding userBinding =
DataBindingUtil. inflate(inflater,R.layout.fragment_main,
container, false);
...
View rootView = userBinding.getRoot();
...
...
User user = …..// get or create the user object
user.setUser(user);
....
....
return rootView}
Conclusion
This is just the overview of Android data binding, however a lot more interesting and powerful features are available in the library which will be covered in the next part.
Find the article on my Medium Blog as well.