SlideShare a Scribd company logo
Data Binding в массы!
Анохин Михаил / Android Developer / MWDN Ltd.
Data Binding
● представлен на Google I/O 2015
● официальная библиотека от Google
● генерирует биндинг во время компиляции
● на данный момент доступна стабильная версия 1.0 и в
процессе разработки находится версия 2.0 2
public class FindViewByIdFragment extends Fragment {
private TextView firstName;
private TextView lastName;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_simple_as_is, container, false);
firstName = (TextView) view.findViewById(R.id.first_name);
lastName = (TextView) view.findViewById(R.id.last_name);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
User user = User.getDefault();
firstName.setText(user.firstName);
lastName.setText(user.lastName);
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
findViewById
3
public class ButterKnifeFragment extends Fragment {
@Bind(R.id.first_name)
TextView firstName;
@Bind(R.id.last_name)
TextView lastName;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_simple_as_is, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
User user = User.getDefault();
firstName.setText(user.firstName);
lastName.setText(user.lastName);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
ButterKnife
4
Binding (Model)
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.anokmik.databinding.model.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.firstName}"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.lastName}"/>
</LinearLayout>
</layout>
public class BindingModelFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_binding_model, container, false);
FragmentBindingModelBinding binding
= FragmentBindingModelBinding.bind(view);
binding.setUser(User.getDefault());
return view;
}
}
5
Binding (Ids)
public class BindingIdsFragment extends Fragment {
private TextView firstName;
private TextView lastName;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_binding_ids, container, false);
FragmentBindingIdsBinding binding
= FragmentBindingIdsBinding.bind(view);
firstName = binding.firstName;
lastName = binding.lastName;
return view;
}
@Override
public void onViewCreated(View view,
Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
User user = User.getDefault();
firstName.setText(user.firstName);
lastName.setText(user.lastName);
}
}
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
6
Data Model
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 firstName;
}
public String getLastName() {
return lastName;
}
}
public class User {
public final String firstName;
public final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
7
Configuration
android {
…
buildToolsVersion "23.0.2"
…
dataBinding {
enabled = true
}
…
}
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}
}
8
Compile-time Generation
View view = inflater.inflate(R.layout.fragment_main, container, false);
FragmentMainBinding binding = FragmentMainBinding.bind(view);
<data class="FragmentMainBinding">
...
</data>
<data class=".FragmentMainBinding">
...
</data>
<data class="com.example.FragmentMainBinding">
...
</data>
9
Generated classes location: /build/intermediates/classes/{$applicationId}/databinding
Variables and Imports
public abstract User getUser();
public abstract void setUser(User user);
public abstract Drawable getImage();
public abstract void setImage(Drawable image);
public abstract String getText();
public abstract void setText(String text);
<data>
<import type="android.graphics.drawable.Drawable" />
<import type="com.anokmik.databinding.model.User" />
<variable name="user" type="User" />
<variable name="image" type="Drawable" />
<variable name="text" type="String" />
</data>
10
Variables and Imports
<data>
<import type="android.util.SparseArray"/>
<import type="java.util.Map"/>
<import type="java.util.List"/>
<variable name="array" type="String[]" />
<variable name="list" type="List&lt;String>"/>
<variable name="sparse" type="SparseArray&lt;String>"/>
<variable name="map" type="Map&lt;String, String>"/>
<variable name="index" type="int"/>
<variable name="key" type="String"/>
</data>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{titles[0]}" />
<data>
<import type="android.app.Fragment"/>
<import type="android.support.v4.app.Fragment" alias="SupportFragment"/>
</data>
11
Data Objects
public class NotifyGreeting extends BaseObservable {
private String name;
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
public class ObservableGreeting {
public ObservableString name
= new ObservableString();
}
12
Include and Merge
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable name="user" type="com.example.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/name"
bind:user="@{user}" />
</LinearLayout>
</layout>
<layout
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable name="user" type="com.example.User"/>
</data>
<merge>
<include layout="@layout/name"
bind:user="@{user}"/>
</merge>
</layout>
13
Expressions
● mathematical +, -, /, *, %
● string concatenation +
● logical &&, ||
● binary &, |, ^
● unary +, -, !, ~
● shift >>, >>>, <<
● comparison ==, >, <, >=, <=
● instanceof
● grouping ()
● literals - character, String, numeric, null
● cast
● method calls
● field access
● array access []
● ternary operator ?:
android:enabled="@{communicator.isLoginValid &amp; communicator.isPasswordValid}"
14
Null
android:text="@{user.firstName ?? user.lastName}"
android:text="@{user.firstName != null ? user.firstName : user.lastName}"
android:visibility="@{communicator.greeting.name.length > 0 ? View.VISIBLE : View.GONE}"
15
Setters
android:text="@{user.firstName}" bind:onClickListener="@{communicator.clickListener}"
bind:textWatcher="@{communicator.loginTextWatcher}" bind:bindingText="@{communicator.greeting.name}"
@BindingAdapter("bind:textWatcher")
public static void setTextWatcher(TextView view,
TextWatcher watcher) {
view.addTextChangedListener(watcher);
}
@BindingAdapter("bind:bindingText")
public static void setBindingText(TextView view,
final ObservableString text) {
view.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable s) {
text.set(s.toString());
}
});
}
16
Converters
public class Converters {
@BindingConversion
public static String convertObservableToString(ObservableString observableString) {
return observableString.get();
}
}
17
Binding executor
18
private static final boolean USE_CHOREOGRAPHER = SDK_INT >= 16;
...
protected ViewDataBinding(DataBindingComponent bindingComponent,
View root, int localFieldCount) {
...
if (USE_CHOREOGRAPHER) {
mChoreographer = Choreographer.getInstance();
mFrameCallback = new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
mRebindRunnable.run();
}
};
} else {
mFrameCallback = null;
mUIThreadHandler = new Handler(Looper.myLooper());
}
}
Binding execution
19
protected void requestRebind() {
...
if (USE_CHOREOGRAPHER) {
mChoreographer.postFrameCallback(mFrameCallback);
} else {
mUIThreadHandler.post(mRebindRunnable);
}
}
private final Runnable mRebindRunnable = new Runnable() {
@Override
public void run() {
...
executePendingBindings();
}
};
public void executePendingBindings() {
...
if (!mRebindHalted) {
executeBindings();
...
}
...
}
Generated binding
20
public class FragmentBindingModelBinding
extends android.databinding.ViewDataBinding {
...
@Override
protected void executeBindings() {
long dirtyFlags = 0;
synchronized(this) {
dirtyFlags = mDirtyFlags;
mDirtyFlags = 0;
}
java.lang.String firstNameUser = null;
java.lang.String lastNameUser = null;
com.anokmik.databinding.model.User user = mUser;
if ((dirtyFlags & 0x3L) != 0) {
user = user;
if (user != null) {
firstNameUser = user.firstName;
lastNameUser = user.lastName;
}
}
if ((dirtyFlags & 0x3L) != 0) {
this.mboundView1.setText(firstNameUser);
this.mboundView2.setText(lastNameUser);
}
}
...
}
New in 2.0-beta
21
Annotations: InverseBindingAdapter,
InverseBindingMethod,
InverseBindingMethods
Interface: InverseBindingListener
References
● http://developer.android.com/tools/data-binding/guide.html
● https://www.youtube.com/watch?v=ssayKH0tudk
● https://www.youtube.com/watch?v=WdUbXWztKNY
● https://realm.io/news/data-binding-android-boyar-mount/
● https://speakerdeck.com/rciovati/binding-data-with-android-databinding
● https://medium.com/@fabioCollini/android-data-binding-f9f9d3afc761
22
Спасибо за внимание!
source: https://github.com/anokmik/data-binding
mail: anokmik@gmail.com
skype: anokmik

More Related Content

PDF
Anton Minashkin Dagger 2 light
PDF
Михаил Анохин "Data binding 2.0"
PDF
"Android Data Binding в массы" Михаил Анохин
PDF
안드로이드 데이터 바인딩
PDF
Backbone Basics with Examples
PDF
Design patterns in Magento
KEY
SOLID Principles
PDF
Data binding в массы!
Anton Minashkin Dagger 2 light
Михаил Анохин "Data binding 2.0"
"Android Data Binding в массы" Михаил Анохин
안드로이드 데이터 바인딩
Backbone Basics with Examples
Design patterns in Magento
SOLID Principles
Data binding в массы!

What's hot (20)

PDF
Effective Android Data Binding
PDF
Modern Android Architecture
PDF
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
PDF
Trustparency web doc spring 2.5 & hibernate
PDF
Windows 8 Training Fundamental - 1
PDF
PDF
Introduction to DI(C)
PPTX
AngularJs $provide API internals & circular dependency problem.
PPTX
PPTX
IndexedDB - Querying and Performance
PDF
TurboGears2 Pluggable Applications
PDF
Rapid development tools for java ee 8 [tut2998]
PDF
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
PDF
Android Jetpack: ViewModel and Testing
KEY
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
PDF
PDF
Android Testing
PDF
Alfredo-PUMEX
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
Effective Android Data Binding
Modern Android Architecture
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
Trustparency web doc spring 2.5 & hibernate
Windows 8 Training Fundamental - 1
Introduction to DI(C)
AngularJs $provide API internals & circular dependency problem.
IndexedDB - Querying and Performance
TurboGears2 Pluggable Applications
Rapid development tools for java ee 8 [tut2998]
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
Android Jetpack: ViewModel and Testing
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Android Testing
Alfredo-PUMEX
Workshop 20: ReactJS Part II Flux Pattern & Redux
Ad

Similar to Data binding в массы! (1.2) (20)

PDF
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
PDF
Data Binding
PDF
MVVM & Data Binding Library
PDF
ButterKnife
PPTX
Data Binding - Android by Harin Trivedi
PDF
How to use data binding in android
PDF
Deep dive into Android Data Binding
PDF
Data binding w Androidzie
PPTX
Data Binding: Is It the Next Big Thing?
PDF
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
PDF
Dominando o Data Binding no Android
PDF
Droidcon Paris 2015
PPTX
Android data binding
PPTX
O que há de novo no Xamarin.Forms
PPTX
Binding data with the AdapterView class.pptx
PDF
Dominando o Data Binding no Android
PDF
Android Support Libraries
PPTX
List adapter with multiple objects
PPTX
Butter knife ppt
PDF
Android Databinding Library
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
Data Binding
MVVM & Data Binding Library
ButterKnife
Data Binding - Android by Harin Trivedi
How to use data binding in android
Deep dive into Android Data Binding
Data binding w Androidzie
Data Binding: Is It the Next Big Thing?
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Dominando o Data Binding no Android
Droidcon Paris 2015
Android data binding
O que há de novo no Xamarin.Forms
Binding data with the AdapterView class.pptx
Dominando o Data Binding no Android
Android Support Libraries
List adapter with multiple objects
Butter knife ppt
Android Databinding Library
Ad

Recently uploaded (20)

PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PDF
Sims 4 Historia para lo sims 4 para jugar
PPTX
PptxGenJS_Demo_Chart_20250317130215833.pptx
PDF
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
PDF
WebRTC in SignalWire - troubleshooting media negotiation
PPTX
artificial intelligence overview of it and more
PDF
Testing WebRTC applications at scale.pdf
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
PPTX
international classification of diseases ICD-10 review PPT.pptx
PDF
Paper PDF World Game (s) Great Redesign.pdf
PPTX
E -tech empowerment technologies PowerPoint
PPTX
Introduction to Information and Communication Technology
PDF
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PPT
tcp ip networks nd ip layering assotred slides
PPTX
Digital Literacy And Online Safety on internet
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
Job_Card_System_Styled_lorem_ipsum_.pptx
Unit-1 introduction to cyber security discuss about how to secure a system
Sims 4 Historia para lo sims 4 para jugar
PptxGenJS_Demo_Chart_20250317130215833.pptx
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
WebRTC in SignalWire - troubleshooting media negotiation
artificial intelligence overview of it and more
Testing WebRTC applications at scale.pdf
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
international classification of diseases ICD-10 review PPT.pptx
Paper PDF World Game (s) Great Redesign.pdf
E -tech empowerment technologies PowerPoint
Introduction to Information and Communication Technology
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
Design_with_Watersergyerge45hrbgre4top (1).ppt
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
tcp ip networks nd ip layering assotred slides
Digital Literacy And Online Safety on internet

Data binding в массы! (1.2)

  • 1. Data Binding в массы! Анохин Михаил / Android Developer / MWDN Ltd.
  • 2. Data Binding ● представлен на Google I/O 2015 ● официальная библиотека от Google ● генерирует биндинг во время компиляции ● на данный момент доступна стабильная версия 1.0 и в процессе разработки находится версия 2.0 2
  • 3. public class FindViewByIdFragment extends Fragment { private TextView firstName; private TextView lastName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate( R.layout.fragment_simple_as_is, container, false); firstName = (TextView) view.findViewById(R.id.first_name); lastName = (TextView) view.findViewById(R.id.last_name); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); User user = User.getDefault(); firstName.setText(user.firstName); lastName.setText(user.lastName); } } <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/first_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/last_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> findViewById 3
  • 4. public class ButterKnifeFragment extends Fragment { @Bind(R.id.first_name) TextView firstName; @Bind(R.id.last_name) TextView lastName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate( R.layout.fragment_simple_as_is, container, false); ButterKnife.bind(this, view); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); User user = User.getDefault(); firstName.setText(user.firstName); lastName.setText(user.lastName); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } } <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/first_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/last_name" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> ButterKnife 4
  • 5. Binding (Model) <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="user" type="com.anokmik.databinding.model.User" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{user.firstName}"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{user.lastName}"/> </LinearLayout> </layout> public class BindingModelFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate( R.layout.fragment_binding_model, container, false); FragmentBindingModelBinding binding = FragmentBindingModelBinding.bind(view); binding.setUser(User.getDefault()); return view; } } 5
  • 6. Binding (Ids) public class BindingIdsFragment extends Fragment { private TextView firstName; private TextView lastName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate( R.layout.fragment_binding_ids, container, false); FragmentBindingIdsBinding binding = FragmentBindingIdsBinding.bind(view); firstName = binding.firstName; lastName = binding.lastName; return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); User user = User.getDefault(); firstName.setText(user.firstName); lastName.setText(user.lastName); } } <layout xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/first_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/last_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> </layout> 6
  • 7. Data Model 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 firstName; } public String getLastName() { return lastName; } } public class User { public final String firstName; public final String lastName; public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } 7
  • 8. Configuration android { … buildToolsVersion "23.0.2" … dataBinding { enabled = true } … } buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' } } 8
  • 9. Compile-time Generation View view = inflater.inflate(R.layout.fragment_main, container, false); FragmentMainBinding binding = FragmentMainBinding.bind(view); <data class="FragmentMainBinding"> ... </data> <data class=".FragmentMainBinding"> ... </data> <data class="com.example.FragmentMainBinding"> ... </data> 9 Generated classes location: /build/intermediates/classes/{$applicationId}/databinding
  • 10. Variables and Imports public abstract User getUser(); public abstract void setUser(User user); public abstract Drawable getImage(); public abstract void setImage(Drawable image); public abstract String getText(); public abstract void setText(String text); <data> <import type="android.graphics.drawable.Drawable" /> <import type="com.anokmik.databinding.model.User" /> <variable name="user" type="User" /> <variable name="image" type="Drawable" /> <variable name="text" type="String" /> </data> 10
  • 11. Variables and Imports <data> <import type="android.util.SparseArray"/> <import type="java.util.Map"/> <import type="java.util.List"/> <variable name="array" type="String[]" /> <variable name="list" type="List&lt;String>"/> <variable name="sparse" type="SparseArray&lt;String>"/> <variable name="map" type="Map&lt;String, String>"/> <variable name="index" type="int"/> <variable name="key" type="String"/> </data> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{titles[0]}" /> <data> <import type="android.app.Fragment"/> <import type="android.support.v4.app.Fragment" alias="SupportFragment"/> </data> 11
  • 12. Data Objects public class NotifyGreeting extends BaseObservable { private String name; @Bindable public String getName() { return name; } public void setName(String name) { this.name = name; notifyPropertyChanged(BR.name); } } public class ObservableGreeting { public ObservableString name = new ObservableString(); } 12
  • 13. Include and Merge <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto"> <data> <variable name="user" type="com.example.User" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/name" bind:user="@{user}" /> </LinearLayout> </layout> <layout xmlns:bind="http://schemas.android.com/apk/res-auto"> <data> <variable name="user" type="com.example.User"/> </data> <merge> <include layout="@layout/name" bind:user="@{user}"/> </merge> </layout> 13
  • 14. Expressions ● mathematical +, -, /, *, % ● string concatenation + ● logical &&, || ● binary &, |, ^ ● unary +, -, !, ~ ● shift >>, >>>, << ● comparison ==, >, <, >=, <= ● instanceof ● grouping () ● literals - character, String, numeric, null ● cast ● method calls ● field access ● array access [] ● ternary operator ?: android:enabled="@{communicator.isLoginValid &amp; communicator.isPasswordValid}" 14
  • 15. Null android:text="@{user.firstName ?? user.lastName}" android:text="@{user.firstName != null ? user.firstName : user.lastName}" android:visibility="@{communicator.greeting.name.length > 0 ? View.VISIBLE : View.GONE}" 15
  • 16. Setters android:text="@{user.firstName}" bind:onClickListener="@{communicator.clickListener}" bind:textWatcher="@{communicator.loginTextWatcher}" bind:bindingText="@{communicator.greeting.name}" @BindingAdapter("bind:textWatcher") public static void setTextWatcher(TextView view, TextWatcher watcher) { view.addTextChangedListener(watcher); } @BindingAdapter("bind:bindingText") public static void setBindingText(TextView view, final ObservableString text) { view.addTextChangedListener(new SimpleTextWatcher() { @Override public void afterTextChanged(Editable s) { text.set(s.toString()); } }); } 16
  • 17. Converters public class Converters { @BindingConversion public static String convertObservableToString(ObservableString observableString) { return observableString.get(); } } 17
  • 18. Binding executor 18 private static final boolean USE_CHOREOGRAPHER = SDK_INT >= 16; ... protected ViewDataBinding(DataBindingComponent bindingComponent, View root, int localFieldCount) { ... if (USE_CHOREOGRAPHER) { mChoreographer = Choreographer.getInstance(); mFrameCallback = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { mRebindRunnable.run(); } }; } else { mFrameCallback = null; mUIThreadHandler = new Handler(Looper.myLooper()); } }
  • 19. Binding execution 19 protected void requestRebind() { ... if (USE_CHOREOGRAPHER) { mChoreographer.postFrameCallback(mFrameCallback); } else { mUIThreadHandler.post(mRebindRunnable); } } private final Runnable mRebindRunnable = new Runnable() { @Override public void run() { ... executePendingBindings(); } }; public void executePendingBindings() { ... if (!mRebindHalted) { executeBindings(); ... } ... }
  • 20. Generated binding 20 public class FragmentBindingModelBinding extends android.databinding.ViewDataBinding { ... @Override protected void executeBindings() { long dirtyFlags = 0; synchronized(this) { dirtyFlags = mDirtyFlags; mDirtyFlags = 0; } java.lang.String firstNameUser = null; java.lang.String lastNameUser = null; com.anokmik.databinding.model.User user = mUser; if ((dirtyFlags & 0x3L) != 0) { user = user; if (user != null) { firstNameUser = user.firstName; lastNameUser = user.lastName; } } if ((dirtyFlags & 0x3L) != 0) { this.mboundView1.setText(firstNameUser); this.mboundView2.setText(lastNameUser); } } ... }
  • 21. New in 2.0-beta 21 Annotations: InverseBindingAdapter, InverseBindingMethod, InverseBindingMethods Interface: InverseBindingListener
  • 22. References ● http://developer.android.com/tools/data-binding/guide.html ● https://www.youtube.com/watch?v=ssayKH0tudk ● https://www.youtube.com/watch?v=WdUbXWztKNY ● https://realm.io/news/data-binding-android-boyar-mount/ ● https://speakerdeck.com/rciovati/binding-data-with-android-databinding ● https://medium.com/@fabioCollini/android-data-binding-f9f9d3afc761 22
  • 23. Спасибо за внимание! source: https://github.com/anokmik/data-binding mail: anokmik@gmail.com skype: anokmik