SlideShare a Scribd company logo
Data Binding
with Android Studio
by
Harin Trivedi
Sr. Software Engineer
OBJECTIVE
➔ Automatic & Dynamic
view binding
➔ Binding data to view
component
◆ Static binding
◆ Dynamic binding
How to enable it ?
Just add below lines of code in app
level build.gradle file.
➔ Available on and above Android
2.1 (Level 7)
➔ Need ‘Android Gradle Plugin’
2.0.0 and above.
➔ After Gradle version 3.1.0 add this
in gradle.properties
android.databinding.enableV2=true
android {
...
dataBinding {
enabled = true
}
}
View Component
binding of
Layout
Need to place layout with root tag
<layout>
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
… // Model to binding
</data>
… // Your layout
</layout>
Generate Binding
Three ways to generate dynamic binding to attached java class
1. Activity
1. Fragment or Other (eg. Adapter row layout)
MainActivityBinding Binding =
DataBindingUtil.setContentView(this,R.layout.main_activity);
OR
MainActivityBinding binding = MainActivityBinding.inflate(getLayoutInflater());
FragmentListBinding binding = DataBindingUtil.inflate(layoutInflater,
R.layout.fragment_list, viewGroup, false);
Binding Data (Model)
Include model class variable inside <data> tag to use in layout
<layout>
<data>
<variable name="user" type="com.example.User"/>
</data>
<LinearLayout ...>
<TextView ...
android:text="@{user.firstName}"/>
<TextView ...
android:text="@{user.lastName}"/>
</LinearLayout>
</layout>
public class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName; }
public String getLastName() {
return this.lastName; }
}
Event Binding
➔ Method Reference :- Direct reference to events (eg. onClick, onItemClick etc.)
➔ Listener Binding :- Reference to event handler (eg. presenter)
android:onClick="@{listener::onClick}"
<CheckBox … android:onCheckedChanged=
"@{(cb, isChecked) ->
presenter.toggleSubscribe(task, isChecked)}"
android:onClick=
"()->presenter.onSaveClick(task)"
public class Presenter {
public void onSaveClick(Task task){}
public void onCompletedChanged(Task task, boolean completed){} }
Injecting Multiple
Type of Data
<data>
<import type="com.example.User"/>
<import type="java.util.List"/>
<import
type="android.graphics.drawable.Drawable"/>
...
<variable name="user"
type="com.example.User"/>
<variable name="image" type="Drawable"/>
<variable name="note" type="String"/>
<variable name="userList"
type="List&lt;User&gt;"/>
</data>
Note :- Auto import is not yet supported.
➔ Primitive Type Objects
◆ Int, float, string etc.
➔ Model
◆ User defined or System class
objects
➔ Collections
◆ List, Map etc.
➔ Drawables
etc.
Include
<include
android:id="+@id/inner_layout_id"
layout="@layout/inner_layout"
bind:user="@{user}"/>
Need to pass bound data to the
included layout.
MainActivityBinding mainBinding;
InnerLayoutBinding innerBinding;
...
innerBinding =
mainBinding.innerLayoutId;
innerBinding.tvTitle.setText(“Hello”);
Expression Language
&
Operators
Examples:
android:visibility="@{age < 18 ? View.GONE :
View.VISIBLE}"
android:visibility="@{item.isFavourite ?
View.VISIBLE : View.GONE}"
android:text="@{user.firstname + ‘ ’ +
user.lastname}"
android:text="@{String.valueOf(index + 1)}"
android:transitionName="@{‘image_’ + id}"
There’s More ...
Attribute Setters
1. Automatic Setters
1. Renamed Setters
If you want ‘itemBackgroundColor’ instead ‘background color’
android:text="@{tiem.title}" // looks for setTitle() in user object
android:background="@{item.bgColor}" // looks for setTitle() in user object
@BindingMethods({
@BindingMethod(type = "android.widget.ImageView",
attribute = "android:background",
method = "setItemBackgroundColor")
})
Public void setItemBackgroundColor(int color) { … }
android:background=
"@{item.itemBackgroundColor}"
Custom Setters (Binding Adapter)
More than setting value, process view and/or apply logic on data.
Public class BindingUtils{
@BindingAdapter({"bind:imageUrl", "bind:error"})
public static void loadImage(ImageView view, String url, Drawable error) {
Picasso.with(view.getContext()).load(url).error(error).into(view);
}
}
<ImageView … app:imageUrl="@{item.imageUrl}"
app:error="@{@drawable/errorDrawable}"/>
Observables
➔ Observable Objects
➔ Observable Fields
➔ Observable Collections
https://developer.android.com/topic/
libraries/data-
binding/index.html#data_objects
➔ Suitable for MVVM
approach.
The real power of data binding can
be used by giving your data objects
the ability to
notify
when
data changes.
Before I forget ...
Two Way Binding
<layout>
<data>
<variable name="user" type="com.example.User"/>
</data>
<LinearLayout ...>
<EditText …
android:text="@={user.firstName}"/>
<EditText …
android:text="@={user.lastName}"/>
</LinearLayout>
</layout>
References
● https://developer.android.com/topic/libr
aries/data-binding/index.html
● https://medium.com/google-
developers/android-data-binding-
recyclerview-db7c40d9f0e4#.n53rmdvsf
● Blog Series:
https://medium.com/@Harry91/android-data-
binding-binding-view-and-data-part-1-
3b9154de09c6
● Github Demo:
https://github.com/HarinTrivedi/MyDataBindin
gExample-master
THANK YOU
Harin Trivedi

More Related Content

PPTX
Sharing Data Between Angular Components
PPTX
React & redux
PPTX
ASP.NET MVC Controllers & Actions
PPTX
Angular JS
PPTX
Web technology javascript
PDF
React JS and Redux
PPTX
Asp.NET MVC
PPTX
Unit 2 - Data Binding.pptx
Sharing Data Between Angular Components
React & redux
ASP.NET MVC Controllers & Actions
Angular JS
Web technology javascript
React JS and Redux
Asp.NET MVC
Unit 2 - Data Binding.pptx

What's hot (20)

PPTX
React JS .NET
PPTX
Introduction to React JS for beginners
PPTX
Controllers & actions
PPTX
Academy PRO: React JS. Redux & Tooling
PPTX
React with Redux
PDF
React state managmenet with Redux
PDF
AngularJS Basic Training
PDF
React.js and Redux overview
PDF
React, Redux, ES2015 by Max Petruck
PPTX
Redux training
PPTX
PPTX
Asp.net mvc training
PPTX
React render props
PPTX
AngularJs Workshop SDP December 28th 2014
PDF
React.js or why DOM finally makes sense
PDF
React & Redux
PDF
Step by Step Asp.Net GridView Tutorials
PPTX
Comparing Angular and React JS for SPAs
PPTX
AngularConf2016 - A leap of faith !?
PDF
Data binding w Androidzie
React JS .NET
Introduction to React JS for beginners
Controllers & actions
Academy PRO: React JS. Redux & Tooling
React with Redux
React state managmenet with Redux
AngularJS Basic Training
React.js and Redux overview
React, Redux, ES2015 by Max Petruck
Redux training
Asp.net mvc training
React render props
AngularJs Workshop SDP December 28th 2014
React.js or why DOM finally makes sense
React & Redux
Step by Step Asp.Net GridView Tutorials
Comparing Angular and React JS for SPAs
AngularConf2016 - A leap of faith !?
Data binding w Androidzie
Ad

Similar to Data Binding - Android by Harin Trivedi (20)

PDF
Data binding 入門淺談
PDF
How to use data binding in android
PDF
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
PDF
Effective Android Data Binding
PDF
"Android Data Binding в массы" Михаил Анохин
PDF
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
PDF
Angular JS2 Training Session #2
PPTX
Data binding в массы! (1.2)
PDF
MVVM & Data Binding Library
PDF
Data Binding
PPTX
React & Redux for noobs
PDF
Михаил Анохин "Data binding 2.0"
PPT
Struts 2 + Spring
PPTX
Mobile App Development: Primi passi con NativeScript e Angular 2
PDF
Introduction to Polymer and Firebase - Simon Gauvin
PDF
Deep dive into Android Data Binding
PPTX
Extend sdk
PDF
I am looking for some assistance with SQLite database. I have tried se.pdf
PPTX
chp 4 progress barjdjjjffjdjd_final.pptx
PDF
Adding custom ui controls to your application (1)
Data binding 入門淺談
How to use data binding in android
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
Effective Android Data Binding
"Android Data Binding в массы" Михаил Анохин
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Angular JS2 Training Session #2
Data binding в массы! (1.2)
MVVM & Data Binding Library
Data Binding
React & Redux for noobs
Михаил Анохин "Data binding 2.0"
Struts 2 + Spring
Mobile App Development: Primi passi con NativeScript e Angular 2
Introduction to Polymer and Firebase - Simon Gauvin
Deep dive into Android Data Binding
Extend sdk
I am looking for some assistance with SQLite database. I have tried se.pdf
chp 4 progress barjdjjjffjdjd_final.pptx
Adding custom ui controls to your application (1)
Ad

Recently uploaded (20)

PDF
AI in Product Development-omnex systems
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
history of c programming in notes for students .pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
ai tools demonstartion for schools and inter college
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Nekopoi APK 2025 free lastest update
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
System and Network Administraation Chapter 3
PDF
Digital Strategies for Manufacturing Companies
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Introduction to Artificial Intelligence
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Operating system designcfffgfgggggggvggggggggg
AI in Product Development-omnex systems
wealthsignaloriginal-com-DS-text-... (1).pdf
Understanding Forklifts - TECH EHS Solution
history of c programming in notes for students .pptx
Odoo Companies in India – Driving Business Transformation.pdf
Odoo POS Development Services by CandidRoot Solutions
ai tools demonstartion for schools and inter college
2025 Textile ERP Trends: SAP, Odoo & Oracle
Nekopoi APK 2025 free lastest update
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
System and Network Administraation Chapter 3
Digital Strategies for Manufacturing Companies
How to Choose the Right IT Partner for Your Business in Malaysia
Introduction to Artificial Intelligence
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Softaken Excel to vCard Converter Software.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Design an Analysis of Algorithms II-SECS-1021-03
Operating system designcfffgfgggggggvggggggggg

Data Binding - Android by Harin Trivedi

  • 1. Data Binding with Android Studio by Harin Trivedi Sr. Software Engineer
  • 2. OBJECTIVE ➔ Automatic & Dynamic view binding ➔ Binding data to view component ◆ Static binding ◆ Dynamic binding
  • 3. How to enable it ? Just add below lines of code in app level build.gradle file. ➔ Available on and above Android 2.1 (Level 7) ➔ Need ‘Android Gradle Plugin’ 2.0.0 and above. ➔ After Gradle version 3.1.0 add this in gradle.properties android.databinding.enableV2=true android { ... dataBinding { enabled = true } }
  • 4. View Component binding of Layout Need to place layout with root tag <layout> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> … // Model to binding </data> … // Your layout </layout>
  • 5. Generate Binding Three ways to generate dynamic binding to attached java class 1. Activity 1. Fragment or Other (eg. Adapter row layout) MainActivityBinding Binding = DataBindingUtil.setContentView(this,R.layout.main_activity); OR MainActivityBinding binding = MainActivityBinding.inflate(getLayoutInflater()); FragmentListBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.fragment_list, viewGroup, false);
  • 6. Binding Data (Model) Include model class variable inside <data> tag to use in layout <layout> <data> <variable name="user" type="com.example.User"/> </data> <LinearLayout ...> <TextView ... android:text="@{user.firstName}"/> <TextView ... android:text="@{user.lastName}"/> </LinearLayout> </layout> public class User { private final String firstName; private final String lastName; public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } }
  • 7. Event Binding ➔ Method Reference :- Direct reference to events (eg. onClick, onItemClick etc.) ➔ Listener Binding :- Reference to event handler (eg. presenter) android:onClick="@{listener::onClick}" <CheckBox … android:onCheckedChanged= "@{(cb, isChecked) -> presenter.toggleSubscribe(task, isChecked)}" android:onClick= "()->presenter.onSaveClick(task)" public class Presenter { public void onSaveClick(Task task){} public void onCompletedChanged(Task task, boolean completed){} }
  • 8. Injecting Multiple Type of Data <data> <import type="com.example.User"/> <import type="java.util.List"/> <import type="android.graphics.drawable.Drawable"/> ... <variable name="user" type="com.example.User"/> <variable name="image" type="Drawable"/> <variable name="note" type="String"/> <variable name="userList" type="List&lt;User&gt;"/> </data> Note :- Auto import is not yet supported. ➔ Primitive Type Objects ◆ Int, float, string etc. ➔ Model ◆ User defined or System class objects ➔ Collections ◆ List, Map etc. ➔ Drawables etc.
  • 9. Include <include android:id="+@id/inner_layout_id" layout="@layout/inner_layout" bind:user="@{user}"/> Need to pass bound data to the included layout. MainActivityBinding mainBinding; InnerLayoutBinding innerBinding; ... innerBinding = mainBinding.innerLayoutId; innerBinding.tvTitle.setText(“Hello”);
  • 10. Expression Language & Operators Examples: android:visibility="@{age < 18 ? View.GONE : View.VISIBLE}" android:visibility="@{item.isFavourite ? View.VISIBLE : View.GONE}" android:text="@{user.firstname + ‘ ’ + user.lastname}" android:text="@{String.valueOf(index + 1)}" android:transitionName="@{‘image_’ + id}"
  • 12. Attribute Setters 1. Automatic Setters 1. Renamed Setters If you want ‘itemBackgroundColor’ instead ‘background color’ android:text="@{tiem.title}" // looks for setTitle() in user object android:background="@{item.bgColor}" // looks for setTitle() in user object @BindingMethods({ @BindingMethod(type = "android.widget.ImageView", attribute = "android:background", method = "setItemBackgroundColor") }) Public void setItemBackgroundColor(int color) { … } android:background= "@{item.itemBackgroundColor}"
  • 13. Custom Setters (Binding Adapter) More than setting value, process view and/or apply logic on data. Public class BindingUtils{ @BindingAdapter({"bind:imageUrl", "bind:error"}) public static void loadImage(ImageView view, String url, Drawable error) { Picasso.with(view.getContext()).load(url).error(error).into(view); } } <ImageView … app:imageUrl="@{item.imageUrl}" app:error="@{@drawable/errorDrawable}"/>
  • 14. Observables ➔ Observable Objects ➔ Observable Fields ➔ Observable Collections https://developer.android.com/topic/ libraries/data- binding/index.html#data_objects ➔ Suitable for MVVM approach. The real power of data binding can be used by giving your data objects the ability to notify when data changes.
  • 15. Before I forget ... Two Way Binding <layout> <data> <variable name="user" type="com.example.User"/> </data> <LinearLayout ...> <EditText … android:text="@={user.firstName}"/> <EditText … android:text="@={user.lastName}"/> </LinearLayout> </layout>
  • 16. References ● https://developer.android.com/topic/libr aries/data-binding/index.html ● https://medium.com/google- developers/android-data-binding- recyclerview-db7c40d9f0e4#.n53rmdvsf ● Blog Series: https://medium.com/@Harry91/android-data- binding-binding-view-and-data-part-1- 3b9154de09c6 ● Github Demo: https://github.com/HarinTrivedi/MyDataBindin gExample-master