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

What's hot

React JS .NET
React JS .NETReact JS .NET
React JS .NET
Jennifer Estrada
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
Binary Studio
 
React with Redux
React with ReduxReact with Redux
React with Redux
Stanimir Todorov
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
Cornel Stefanache
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Redux training
Redux trainingRedux training
Redux training
dasersoft
 
React и redux
React и reduxReact и redux
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
icubesystem
 
React render props
React render propsReact render props
React render props
Saikat Samanta
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes sense
Eldar Djafarov
 
React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView Tutorials
Nilesh kumar Jadav
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAsComparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?
Alessandro Giorgetti
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
The Software House
 

What's hot (20)

React JS .NET
React JS .NETReact JS .NET
React JS .NET
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
 
Redux training
Redux trainingRedux training
Redux training
 
React и redux
React и reduxReact и redux
React и redux
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
React render props
React render propsReact render props
React render props
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes sense
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView Tutorials
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAsComparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 

Similar to Data Binding - Android by Harin Trivedi

Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
awonwon
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
InnovationM
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
Inhacking
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
Eric Maxwell
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин
Fwdays
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
Yurii Kotov
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
10Clouds
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"
Fwdays
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
Bryan Hsueh
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2
Filippo Matteo Riggio
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
Simon Gauvin
 
Deep dive into Android Data Binding
Deep dive into Android Data BindingDeep dive into Android Data Binding
Deep dive into Android Data Binding
Radek Piekarz
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
Conint29
 
Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Oro Inc.
 
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
NHN FORWARD
 

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

Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Data Binding
Data BindingData Binding
Data Binding
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
Deep dive into Android Data Binding
Deep dive into Android Data BindingDeep dive into Android Data Binding
Deep dive into Android Data Binding
 
Extend sdk
Extend sdkExtend sdk
Extend sdk
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)
 
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
 

Recently uploaded

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 

Recently uploaded (20)

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 

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