- Урок 8. Android Data Binding – основы
- Data Binding Library
- С чего начать
- Что нам понадобится
- Подключаем Data Binding в проект
- Урок 19. Android Data Binding. Код в layout. Доступ к View
- Урок 23. Android Data Binding. Использование с include, ViewStub и RecyclerView.
- include
- ViewStub
- RecyclerView
- Data Binding Guide
- In this document:
- Beta release
- Build Environment
- Data Binding Layout Files
- Writing your first data binding expressions
- Data Object
- Binding Data
- Binding Events
- Layout Details
- Imports
- Variables
- Custom Binding Class Names
- Includes
- Expression Language
- Common Features
- Missing Operations
- Null Coalescing Operator
- Property Reference
- Avoiding NullPointerException
- Collections
- String Literals
- Resources
- Data Objects
- Observable Objects
- ObservableFields
- Observable Collections
- Generated Binding
- Creating
- Views With IDs
- Variables
- ViewStubs
- Advanced Binding
- Dynamic Variables
- Immediate Binding
- Background Thread
- Attribute Setters
- Automatic Setters
- Renamed Setters
- Custom Setters
- Converters
- Object Conversions
- Custom Conversions
Урок 8. Android Data Binding – основы
Продолжаем курс по обучению основам разработки мобильных приложений в Android Studio на языке Kotlin. В этом уроке познакомимся с Android Data Binding.
Data Binding Library
Библиотека Data Binding Library, которая является частью Android Jetpack, позволяет привязывать компоненты пользовательского интерфейса в макетах к источникам данных в приложении, используя декларативный формат, а не программно. Другими словами, Data Binding поможет организовать работу с View так, чтобы нам не пришлось писать кучу методов findViewById, setText, setOnClickListener и т.п.
Чтобы более тесно на практике познакомиться с чистой архитектурой и архитектурными компонентами, записывайтесь на продвинутый курс по разработке приложения «Чат-мессенжер»
В этом цикле уроков вы узнаете, как настроить Data Binding в проекте, что такое layout expressions, как работать с observable objects и как создавать кастомные Binding Adapters чтобы свести избыточность (boilerplate) вашего кода к минимуму.
С чего начать
В этом уроке, мы возьмем уже существующий проект и конвертируем его в Data Binding:
Приложение имеет один экран, который показывает некоторые статические данные и некоторые наблюдаемые данные, что означает, что при изменении данных пользовательский интерфейс будет автоматически обновляться. Данные предоставлены ViewModel. Model-View-ViewModel — это шаблон уровня представления, который очень хорошо работает с Data Binding. Вот диаграмма паттерна MVVM:
Если вы еще не знакомы с классом ViewModel из библиотек компонентов архитектуры, вы можете посмотреть официальную документацию. Мы знакомились с этим классом на прошлом уроке, ссылку на который вы видите в правом верхнем углу этого видео. Это класс, который предоставляет состояние пользовательского интерфейса для представления (Activity, Fragment, т.п.). Он выдерживает изменения ориентации и действует как интерфейс для остальных слоев вашего приложения.
Что нам понадобится
- Среда разработки Android Studio 3.4 или более новой версии.
- Приложение без Data Binding
На этом этапе мы загрузим и запустим простое приложение-пример. Выполните в консоли команду:
Вы также можете клонировать или скачать репозиторий в виде Zip-файла по ссылке на GitHub
- Распакуйте проект
- Откройте проект в Android Studio версии 3.4 или выше.
- Запустите приложение
Экран по умолчанию открывается и выглядит так:
Этот экран отображает несколько различных полей и кнопку, по нажатию которой можно увеличить счетчик, обновить индикатор выполнения и изображение. Логика действий, происходящих на экране, описана в классе SimpleViewModel. Откройте его и посмотрите.
Используйте Ctrl + N, чтобы быстро найти класс в Android Studio. Используйте Ctrl + Shift + N, чтобы найти файл по его имени.
На Mac найдите класс с помощью Command + O и файл с помощью Command + Shift + O.
В классе SimpleViewModel описаны такие поля:
- Имя и фамилия
- Количество лайков
- Уровень популярности
Кроме того, он позволяет пользователю увеличивать количество лайков методом onLike().
Пока SimpleViewModel содержит не самый интересный функционал, но здесь все в порядке. С другой стороны, класс главного экрана MainActivity имеет ряд проблем:
- Он вызывает метод findViewById несколько раз. Это не только медленно, но и небезопасно, потому что не проверяется на ошибки времени компиляции. Если идентификатор, который вы передаете в findViewById, неправильный, приложение аварийно завершит работу во время выполнения.
- Устанавливает начальные значения в onCreate. Было бы намного лучше иметь значения по умолчанию, которые устанавливаются автоматически.
- Использует в макете атрибут android:onClick который также не является безопасным: если метод onLike не реализован в активити (или переименован), приложение упадет в рантайме.
- В нем много кода. Активити и фрагменты имеют тенденцию расти очень быстро, поэтому желателно удалить из них как можно больше кода. Кроме того, код в активити и фрагментах трудно тестировать и поддерживать.
В нашей серии уроков с помощью библиотеки Data Binding мы собираемся исправить все эти проблемы, переместив логику из активити в места, где ее можно повторно использовать и проще тестировать.
Подключаем Data Binding в проект
Первым шагом является включение библиотеки Data Binding в модули, которые будут ее использовать. Добавьте такие строки в файл сборки модуля app:
Источник
Урок 19. Android Data Binding. Код в layout. Доступ к View
В этом уроке рассматриваем возможность написания кода в layout и получаем View от биндинга.
Полный список уроков курса:
Продолжаем говорить про DataBinding. Мы уже рассмотрели, как можно помещать значения из объектов в TextView. Но биндинг этим не ограничивается и дает нам возможность писать код прямо в layout.
Давайте рассмотрим примеры, когда это может понадобиться.
Есть класс Employee:
Мы хотим выводить на экран имя, адрес и зарплату.
Экран будет таким:
А вызов биндинга таким:
Ничего необычного. Все так же, как и в прошлом уроке.
Но при запуске получим ошибку: android.content.res.Resources$NotFoundException: String resource ID #0x2710
Так произошло, потому что биндинг попытался отобразить поле salary в TextView. Он просто выполнил код setText(employee.salary). И т.к. salary у нас имеет тип int, то TextView решил, что ему передают идентификатор строкового ресурса. И, конечно, он не нашел такую строку в strings.xml.
Это довольно часто возникающая ошибка. И в коде мы обычно решаем ее с помощью String.valueOf():
Биндинг позволяет сделать нам то же самое прямо в layout:
Т.е. внутри @ < . >мы можем писать простейший код и он будет выполнен.
Запустив приложение, мы увидим зарплату в TextView.
Рассмотрим еще несколько примеров:
Отображение в одном TextView сразу двух полей Employee
Обратите внимание на кавычки. Т.к. нам нужны двойные кавычки, чтобы добавить запятую между name и address, то весь этот код мы помещаем в одинарные кавычки.
Видимость View в зависимости от значения поля
Адрес будет отображен, только если он не пустой. А при пустом адресе видимость этого TextView будет GONE.
Обратите внимание, что мы здесь используем классы TextUtils и View. Если сейчас попытаться запустить приложение, то мы получим следующую ошибку: Identifiers must have user defined types from the XML file. TextUtils is missing it
Биндинг говорит, что не знает ничего про TextUtils. Нам надо добавить его в import. Делается это в секции data.
Теперь биндинг знает, какие классы мы имеем ввиду
Т.е. это аналогично тому, как в java коде вы пишете:
и после этого можете использовать эти классы.
Использование resources значения: strings, dimens и пр.
Если адрес пустой, то показываем заглушку из strings.
В примерах выше мы использовали в layout только одну переменную — Employee. Давайте добавим еще одну.
Создадим новый класс, который будет содержать информацию об отделе
Добавим переменную типа Department в layout
И используем ее:
В одном TextView показываем данные из двух переменных.
Код выполнения биндинга будет выглядеть так:
Для переменной Department в классе MainActivityBinding был сгенерирован отдельный метод setDepartment.
Можно немного усложнить логику и показывать название отдела, только если мы передали объект Department в биндинг:
Показываем отдел, если department не null
Биндинг умеет работать и с коллекциями. Например, если в Employee есть поле со списком хобби:
то, в layout мы можем отобразить первое хобби из списка следующим образом:
Если нам необходимо использовать список, как отдельную переменную в layout, то variable будет выглядеть так:
Ограничения XML не позволяют просто так использовать символы . Поэтому их приходится заменять спецсимволами .
То же самое описание переменной, но List вынесен в импорт:
Map коллекции описываются аналогично:
Получение значения по ключу:
В официальной документации вы можете посмотреть полный список возможностей написания кода в layout.
Если нам нужны какие-либо View из нашего layout, то их можно получить из биндинга. Для этого необходимо, чтобы View имело id.
Например, если в layout есть поле:
то мы можем получить его из биндинга так:
Также можно получить корневое View методом getRoot:
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Урок 23. Android Data Binding. Использование с include, ViewStub и RecyclerView.
В этом уроке рассмотрим примеры использование Android Data Binding с include, ViewStub и RecyclerView
Полный список уроков курса:
include
Предполагается, что вы знакомы с тегом include, я не буду подробно о нем рассказывать.
С помощью include можно использовать layout файл внутри другого layout файла. При этом мы можем использовать биндинг без каких-либо дополнительных усилий.
Рассмотрим простой пример.
Основной layout файл main_activity.xml
В include мы указываем, что здесь надо использовать layout из файла employee_details, и передаем переменную, которая этому вложенному layout понадобится.
Файл employee_details.xml выглядит, как обычный layout файл с биндингом.
Он получит переменную employee из внешнего layout и сможет использовать ее значения.
ViewStub
Предполагается, что вы знакомы с механизмом ViewStub, я не буду о нем подробно рассказывать.
ViewStub — это механизм для ленивого создания View. Т.е. если у вас в layout есть View, которые отображаются в исключительных случаях, то нет смысла создавать их при каждом отображении экрана. В этом случае лучше использовать ViewStub, который сможет создать эти View при необходимости.
Я не буду подробно объяснять работу этого механизма, чтобы не перегружать урок. Покажу только, как с ним использовать биндинг.
Рассмотрим пример. У нас есть экран, на котором мы отображаем employee.name.
А вот адрес нам надо отображать крайне редко (по нажатию на какую-то кнопку или если он не пустой). И мы решаем, что будем использовать ViewStub. В его параметре layout указываем имя layout файла (employee_address), который должен будет отображаться, когда мы попросим об этом ViewStub.
Layout файл employee_address.xml — это обычный layout файл с биндингом:
Первые три строки понятны: создаем Employee, получаем биндинг и передаем Employee в биндинг. Этот код сработает для основного layout, и employee.name будет отображен на экране.
Но layout, указанный в ViewStub, мы будем создавать позже (если вообще будем). И после того, как мы его создадим, нам надо будет создать для него отдельный биндинг и передать в этот биндинг данные (Employee).
Используем OnInflateListener, который сработает при создании layout в ViewStub. В onInflate мы получим View, созданный из employee_address.xml. Для этого View методом DataBindingUtil.bind создаем биндинг и передаем туда Employee. Таким образом адрес попадет в TextView.
Обработчик готов. Но сработает он только тогда, когда мы надумаем создать layout из ViewStub. А сделать это можно так:
Проверяем, что из этого ViewStub еще не создавался layout, и запускаем процесс создания.
binding.employeeAddressStub возвращает нам не сам ViewStub, а обертку над ним. Это сделано потому, что ViewStub будет заменен созданным layout и его больше не будет в иерархии View. Соответственно, к нему нельзя будет обратиться. А обертка продолжит жить.
RecyclerView
Рассмотрим пример, как использовать биндинг для элементов списка RecylerView
layout элемента списка выглядит так
Будем выводить только имя работника
Обычно холдеры, которые мы пишем, в свой конструктор ожидают получить View. Но в случае использования биндингом, нам нужен будет объект EmployeeItemBinding — биндинг класс для layout элемента списка.
Методом getRoot мы получим View из этого биндинга и передадим его в конструктор суперкласса.
В метод bind мы будем получать Employee и нам останется только передать его в биндинг, который за нас раскидает значения по View. Метод executePendingBindings используется, чтобы биндинг не откладывался, а выполнился как можно быстрее. Это критично в случае с RecyclerView.
В onCreateViewHolder получаем LayoutInflater. Затем методом DataBindingUtil.inflate создаем биндинг, который будет содержать в себе View, созданный из R.layout.employee_item. Этот биндинг передаем в конструктор холдера.
В onBindViewHolder получаем employee из items и передаем его в bind метод холдера, тем самым запуская биндинг, который заполнит View данными из employee.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Data Binding Guide
In this document:
This document explains how to use the Data Binding Library to write declarative layouts and minimize the glue code necessary to bind your application logic and layouts.
The Data Binding Library offers both flexibility and broad comnpatibility — it’s a support library, so you can use it with all Android platform versions back to Android 2.1 (API level 7+).
To use data binding, Android Plugin for Gradle 1.3.0-beta4 or higher is required.
Beta release
Please note that the Data Binding library is a beta release. While Data Binding is in beta, developers should be aware of the following caveats:
- This is a beta release of the feature intended to generate developer feedback. It might contain bugs, and it might not work for your use case, so use it at your own risk. That said, we do want your feedback! Please let us know what is or isn’t working for you using the issue tracker.
- The Data Binding library beta release is subject to significant changes, including those which are not source code compatible with your app. That is, significant rework may be required to take updates to the library in the future.
- Developers should feel free to publish apps built with the Data Binding library beta release, with the caveats that the standard Android SDK and Google Play terms of service apply, and it’s always a great idea to test your app thoroughly when adopting new libraries or tools.
- We’re just getting started with Android Studio support at this time. Further Android Studio support will come in the future.
- By using the Data Binding library beta release, you acknowledge these caveats.
Build Environment
To get started with Data Binding, download the library from the Support repository in the Android SDK manager.
The Data Binding plugin requires Android Plugin for Gradle 1.3.0-beta4 or higher, so update your build dependencies (in the top-level build.gradle file) as needed.
Also, make sure you are using a compatible version of Android Studio. Android Studio 1.3 adds the code-completion and layout-preview support for data binding.
Setting Up Work Environment:
To set up your application to use data binding, add data binding to the class path of your top-level build.gradle file, right below «android».
Then make sure jcenter is in the repositories list for your projects in the top-level build.gradle file.
In each module you want to use data binding, apply the plugin right after android plugin
The data binding plugin is going to add necessary provided and compile configuration dependencies to your project.
Data Binding Layout Files
Writing your first data binding expressions
Data-binding layout files are slightly different and start with a root tag of layout followed by a data element and a view root element. This view element is what your root would be in a non-binding layout file. A sample file looks like this:
The user variable within data describes a property that may be used within this layout.
Expressions within the layout are written in the attribute properties using the “ @<> ” syntax. Here, the TextView’s text is set to the firstName property of user:
Data Object
Let’s assume for now that you have a plain-old Java object (POJO) for User:
This type of object has data that never changes. It is common in applications to have data that is read once and never changes thereafter. It is also possible to use a JavaBeans objects:
From the perspective of data binding, these two classes are equivalent. The expression @ used for the TextView’s android:text attribute will access the firstName field in the former class and the getFirstName() method in the latter class. Alternatively, it will also be resolved to firstName() if that method exists.
Binding Data
By default, a Binding class will be generated based on the name of the layout file, converting it to Pascal case and suffixing “Binding” to it. The above layout file was main_activity.xml so the generate class was MainActivityBinding . This class holds all the bindings from the layout properties (e.g. the user variable) to the layout’s Views and knows how to assign values for the binding expressions.The easiest means for creating the bindings is to do it while inflating:
You’re done! Run the application and you’ll see Test User in the UI. Alternatively, you can get the view via:
If you are using data binding items inside a ListView or RecyclerView adapter, you may prefer to use:
Binding Events
Events may be bound to handler methods directly, similar to the way android:onClick can be assigned to a method in the Activity. Event attribute names are governed by the name of the listener method with a few exceptions. For example, View.OnLongClickListener has a method onLongClick() , so the attribute for this event is android:onLongClick .
To assign an event to its handler, use a normal binding expression, with the value being the method name to call. For example, if your data object has two methods:
The binding expression can assign the click listener for a View:
Layout Details
Imports
Zero or more import elements may be used inside the data element. These allow easy reference to classes inside your layout file, just like in Java.
Now, View may be used within your binding expression:
When there are class name conflicts, one of the classes may be renamed to an “alias:”
Now, Vista may be used to reference the com.example.real.estate.View and View may be used to reference android.view.View within the layout file. Imported types may be used as type references in variables and expressions:
Note: Android Studio does not yet handle imports so the autocomplete for imported variables may not work in your IDE. Your application will still compile fine and you can work around the IDE issue by using fully qualified names in your variable definitions.
Imported types may also be used when referencing static fields and methods in expressions:
Just as in Java, java.lang.* is imported automatically.
Variables
Any number of variable elements may be used inside the data element. Each variable element describes a property that may be set on the layout to be used in binding expressions within the layout file.
The variable types are inspected at compile time, so if a variable implements Observable or is an observable collection, that should be reflected in the type. If the variable is a base class or interface that does not implement the Observable* interface, the variables will not be observed!
When there are different layout files for various configurations (e.g. landscape or portrait), the variables will be combined. There must not be conflicting variable definitions between these layout files.
The generated binding class will have a setter and getter for each of the described variables. The variables will take the default Java values until the setter is called — null for reference types, 0 for int , false for boolean , etc.
Custom Binding Class Names
By default, a Binding class is generated based on the name of the layout file, starting it with upper-case, removing underscores ( _ ) and capitalizing the following letter and then suffixing “Binding”. This class will be placed in a databinding package under the module package. For example, the layout file contact_item.xml will generate ContactItemBinding . If the module package is com.example.my.app , then it will be placed in com.example.my.app.databinding .
Binding classes may be renamed or placed in different packages by adjusting the class attribute of the data element. For example:
This generates the binding class as ContactItem in the databinding package in the module package. If the class should be generated in a different package within the module package, it may be prefixed with “.”:
In this case, ContactItem is generated in the module package directly. Any package may be used if the full package is provided:
Includes
Variables may be passed into an included layout’s binding from the containing layout by using the application namespace and the variable name in an attribute:
Here, there must be a user variable in both the name.xml and contact.xml layout files.
Data binding does not support include as a direct child of a merge element. For example, the following layout is not supported:
Expression Language
Common Features
The expression language looks a lot like a Java expression. These are the same:
- Mathematical + — / * %
- String concatenation +
- Logical && ||
- Binary & | ^
- Unary + — !
Missing Operations
A few operations are missing from the expression syntax that you can use in Java.
- this
- super
- new
- Explicit generic invocation
Null Coalescing Operator
The null coalescing operator ( ?? ) chooses the left operand if it is not null or the right if it is null.
This is functionally equivalent to:
Property Reference
The first was already discussed in the Writing your first data binding expressions above: short form JavaBean references. When an expression references a property on a class, it uses the same format for fields, getters, and ObservableFields.
Avoiding NullPointerException
Generated data binding code automatically checks for nulls and avoid null pointer exceptions. For example, in the expression @
Collections
Common collections: arrays, lists, sparse lists, and maps, may be accessed using the [] operator for convenience.
String Literals
When using single quotes around the attribute value, it is easy to use double quotes in the expression:
It is also possible to use double quotes to surround the attribute value. When doing so, String literals should either use the » or back quote (`).
Resources
It is possible to access resources as part of expressions using the normal syntax:
Format strings and plurals may be evaluated by providing parameters:
When a plural takes multiple parameters, all parameters should be passed:
Some resources require explicit type evaluation.
Type | Normal Reference | Expression Reference |
---|---|---|
String[] | @array | @stringArray |
int[] | @array | @intArray |
TypedArray | @array | @typedArray |
Animator | @animator | @animator |
StateListAnimator | @animator | @stateListAnimator |
color int | @color | @color |
ColorStateList | @color | @colorStateList |
Data Objects
Any plain old Java object (POJO) may be used for data binding, but modifying a POJO will not cause the UI to update. The real power of data binding can be used by giving your data objects the ability to notify when data changes. There are three different data change notification mechanisms, Observable objects, observable fields, and observable collections.
When one of these observable data object is bound to the UI and a property of the data object changes, the UI will be updated automatically.
Observable Objects
A class implementing the Observable interface will allow the binding to attach a single listener to a bound object to listen for changes of all properties on that object.
The Observable interface has a mechanism to add and remove listeners, but notifying is up to the developer. To make development easier, a base class, BaseObservable , was created to implement the listener registration mechanism. The data class implementer is still responsible for notifying when the properties change. This is done by assigning a Bindable annotation to the getter and notifying in the setter.
The Bindable annotation generates an entry in the BR class file during compilation. The BR class file will be generated in the module package. If the base class for data classes cannot be changed, the Observable interface may be implemented using the convenient PropertyChangeRegistry to store and notify listeners efficiently.
ObservableFields
A little work is involved in creating Observable classes, so developers who want to save time or have few properties may use ObservableField and its siblings ObservableBoolean , ObservableByte , ObservableChar , ObservableShort , ObservableInt , ObservableLong , ObservableFloat , ObservableDouble , and ObservableParcelable . ObservableFields are self-contained observable objects that have a single field. The primitive versions avoid boxing and unboxing during access operations. To use, create a public final field in the data class:
That’s it! To access the value, use the set and get accessor methods:
Observable Collections
Some applications use more dynamic structures to hold data. Observable collections allow keyed access to these data objects. ObservableArrayMap is useful when the key is a reference type, such as String.
In the layout, the map may be accessed through the String keys:
ObservableArrayList is useful when the key is an integer:
In the layout, the list may be accessed through the indices:
Generated Binding
The generated binding class links the layout variables with the Views within the layout. As discussed earlier, the name and package of the Binding may be customized. The Generated binding classes all extend ViewDataBinding .
Creating
The binding should be created soon after inflation to ensure that the View hierarchy is not disturbed prior to binding to the Views with expressions within the layout. There are a few ways to bind to a layout. The most common is to use the static methods on the Binding class.The inflate method inflates the View hierarchy and binds to it all it one step. There is a simpler version that only takes a LayoutInflater and one that takes a ViewGroup as well:
If the layout was inflated using a different mechanism, it may be bound separately:
Sometimes the binding cannot be known in advance. In such cases, the binding can be created using the DataBindingUtil class:
Views With IDs
A public final field will be generated for each View with an ID in the layout. The binding does a single pass on the View hierarchy, extracting the Views with IDs. This mechanism can be faster than calling findViewById for several Views. For example:
Will generate a binding class with:
IDs are not nearly as necessary as without data binding, but there are still some instances where access to Views are still necessary from code.
Variables
Each variable will be given accessor methods.
will generate setters and getters in the binding:
ViewStubs
ViewStub s are a little different from normal Views. They start off invisible and when they either are made visible or are explicitly told to inflate, they replace themselves in the layout by inflating another layout.
Because the ViewStub essentially disappears from the View hierarchy, the View in the binding object must also disappear to allow collection. Because the Views are final, a ViewStubProxy object takes the place of the ViewStub , giving the developer access to the ViewStub when it exists and also access to the inflated View hierarchy when the ViewStub has been inflated.
When inflating another layout, a binding must be established for the new layout. Therefore, the ViewStubProxy must listen to the ViewStub ‘s ViewStub.OnInflateListener and establish the binding at that time. Since only one can exist, the ViewStubProxy allows the developer to set an OnInflateListener on it that it will call after establishing the binding.
Advanced Binding
Dynamic Variables
At times, the specific binding class won’t be known. For example, a RecyclerView.Adapter operating against arbitrary layouts won’t know the specific binding class. It still must assign the binding value during the onBindViewHolder(VH, int) .
In this example, all layouts that the RecyclerView binds to have an «item» variable. The BindingHolder has a getBinding method returning the ViewDataBinding base.
Immediate Binding
When a variable or observable changes, the binding will be scheduled to change before the next frame. There are times, however, when binding must be executed immediately. To force execution, use the executePendingBindings() method.
Background Thread
You can change your data model in a background thread as long as it is not a collection. Data binding will localize each variable / field while evaluating to avoid any concurrency issues.
Attribute Setters
Whenever a bound value changes, the generated binding class must call a setter method on the View with the binding expression. The data binding framework has ways to customize which method to call to set the value.
Automatic Setters
For example, an expression associated with TextView’s attribute android:text will look for a setText(String). If the expression returns an int, data binding will search for a setText(int) method. Be careful to have the expression return the correct type, casting if necessary. Note that data binding will work even if no attribute exists with the given name. You can then easily «create» attributes for any setter by using data binding. For example, support DrawerLayout doesn’t have any attributes, but plenty of setters. You can use the automatic setters to use one of these.
Renamed Setters
Some attributes have setters that don’t match by name. For these methods, an attribute may be associated with the setter through BindingMethods annotation. This must be associated with a class and contains BindingMethod annotations, one for each renamed method. For example, the android:tint attribute is really associated with setImageTintList(ColorStateList) , not setTint .
It is unlikely that developers will need to rename setters; the android framework attributes have already been implemented.
Custom Setters
Some attributes need custom binding logic. For example, there is no associated setter for the android:paddingLeft attribute. Instead, setPadding(left, top, right, bottom) exists. A static binding adapter method with the BindingAdapter annotation allows the developer to customize how a setter for an attribute is called.
The android attributes have already had BindingAdapter s created. For example, here is the one for paddingLeft :
Binding adapters are useful for other types of customization. For example, a custom loader can be called off-thread to load an image.
Developer-created binding adapters will override the data binding default adapters when there is a conflict.
You can also have adapters that receive multiple parameters.
This adapter will be called if both imageUrl and error are used for an ImageView and imageUrl is a string and error is a drawable.
- Custom namespaces are ignored during matching.
- You can also write adapters for android namespace.
Binding adapter methods may optionally take the old values in their handlers. A method taking old and new values should have all old values for the attributes come first, followed by the new values:
Event handlers may only be used with interfaces or abstract classes with one abstract method. For example:
When a listener has multiple methods, it must be split into multiple listeners. For example, View.OnAttachStateChangeListener has two methods: onViewAttachedToWindow() and onViewDetachedFromWindow() . We must then create two interfaces to differentiate the attributes and handlers for them.
Because changing one listener will also affect the other, we must have three different binding adapters, one for each attribute and one for both, should they both be set.
The above example is slightly more complicated than normal because View uses add and remove for the listener instead of a set method for View.OnAttachStateChangeListener . The android.databinding.adapters.ListenerUtil class helps keep track of the previous listeners so that they may be removed in the Binding Adaper.
By annotating the interfaces OnViewDetachedFromWindow and OnViewAttachedToWindow with @TargetApi(VERSION_CODES.HONEYCOMB_MR1) , the data binding code generator knows that the listener should only be generated when running on Honeycomb MR1 and new devices, the same version supported by addOnAttachStateChangeListener(View.OnAttachStateChangeListener) .
Converters
Object Conversions
When an Object is returned from a binding expression, a setter will be chosen from the automatic, renamed, and custom setters. The Object will be cast to a parameter type of the chosen setter.
This is a convenience for those using ObservableMaps to hold data. for example:
The userMap returns an Object and that Object will be automatically cast to parameter type found in the setter setText(CharSequence) . When there may be confusion about the parameter type, the developer will need to cast in the expression.
Custom Conversions
Sometimes conversions should be automatic between specific types. For example, when setting the background:
Here, the background takes a Drawable , but the color is an integer. Whenever a Drawable is expected and an integer is returned, the int should be converted to a ColorDrawable . This conversion is done using a static method with a BindingConversion annotation:
Note that conversions only happen at the setter level, so it is not allowed to mix types like this:
Источник