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 :

// enable data binding for the application
android {
    ......
    dataBinding {
        enabled = true
    }
}
<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>
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content
   android:text="@{user.name}" />
@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);
}
@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}

Find the article on my  Medium Blog as well.

Similar Articles

Leave a Reply