From ea1f6fb385d6f8d19ef18b196b9749dfc74e6cdc Mon Sep 17 00:00:00 2001 From: Dirk Dougherty Date: Tue, 26 May 2015 20:31:12 -0700 Subject: Doc change: edits and fixes to data binding guide. Change-Id: Iaef989bd48a99294e2032656653e71ef93313687 --- docs/html/develop/index.jd | 2 +- docs/html/distribute/tools/open-distribution.jd | 8 - docs/html/google/index.jd | 2 +- docs/html/preview/samples.jd | 2 +- docs/html/tools/data-binding/guide.jd | 1579 +++++++++++++++-------- docs/html/tools/data-binding/index.jd | 4 +- docs/html/tools/tools_toc.cs | 1 - 7 files changed, 1057 insertions(+), 541 deletions(-) (limited to 'docs/html') diff --git a/docs/html/develop/index.jd b/docs/html/develop/index.jd index 17db9e5..bbd2f71 100644 --- a/docs/html/develop/index.jd +++ b/docs/html/develop/index.jd @@ -97,7 +97,7 @@ excludeFromSuggestions=true

Ubiquitous computing on Android

- Opening up new stuff. + A great experience for your users across devices.

- Note: The Install Now button, shown in - Figure 1, appears only if the user has configured their device to allow - installation from unknown sources and - opened your email in the native Gmail app. -

- -

Distributing apps through email is convenient if you’re sending them to a few trusted users, as it provides few protections from piracy and unauthorized distribution; that is, anyone you send your apps to can simply forward them diff --git a/docs/html/google/index.jd b/docs/html/google/index.jd index a4190c9..e3b2ae1 100644 --- a/docs/html/google/index.jd +++ b/docs/html/google/index.jd @@ -11,7 +11,7 @@ footer.hide=1

- +

Build better apps with Google

diff --git a/docs/html/preview/samples.jd b/docs/html/preview/samples.jd index 29b9e2a..21d4215 100644 --- a/docs/html/preview/samples.jd +++ b/docs/html/preview/samples.jd @@ -1,5 +1,5 @@ page.title=Samples -page.image=images/cards/card-samples_16-9_2x.png +page.image=images/cards/samples-new_2x.png @jd:body

diff --git a/docs/html/tools/data-binding/guide.jd b/docs/html/tools/data-binding/guide.jd index 49b690f..6a933d8 100644 --- a/docs/html/tools/data-binding/guide.jd +++ b/docs/html/tools/data-binding/guide.jd @@ -1,121 +1,259 @@ page.title=Data Binding Guide - +page.tags="databinding", "layouts" @jd:body -

Data Binding allows you write declarative layouts and minimize the glue code -that is necessary to bind your application logic and layouts.

- - -

Build Environment

+
+

+The Android Data Binding Library is available as a developer +preview. Expression syntax and behaviors may change prior to the full release +of the library, currently planned for Q3 2015. If you have feedback or want to report +issues, please use the issue +tracker. Stay tuned for more information about Data Binding and examples of how to use it. +

+
+
+ +
+ + +

+ 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. +

-

Setting Up Work Environment:

- -

Data Binding EAP only supports gradle.

- -

To set up your application, unzip the provided bundle to a location. It has 3 -sections

+

+ Build Environment +

-
    -
  • maven-repo: which keeps the data-binding libraries -
  • samples: Sample applications -
  • databinding.properties: Properties file that can be used to integrate with your app -
+

+ Setting Up Work Environment: +

-

Add the following section to the project’s build.gradle file (not the module's -build.gradle) and replace with the absolute path of the bundle that you’ve unzipped in the previous step.

+

+ To set up your application to use data binding, add data binding to the class + path of your build gradle file, right below "android". +

-
-buildscript {
-   def eapFolder = '<BUNDLE_FOLDER>'
-   def Properties props = new Properties()
-   props.load(new FileInputStream("${eapFolder}/databinding.properties"))
-   props.mavenRepoDir = "${eapFolder}/${props.mavenRepoName}"
-   ext.config = props
-   repositories {
-       jcenter()
-       maven {
-           url config.mavenRepoDir
-       }
-   }
+
    dependencies {
-       classpath "com.android.tools.build:gradle:1.1.3"
-       classpath "com.android.databinding:dataBinder:${config.snapshotVersion}"
-   }
+       classpath "com.android.tools.build:gradle:1.2.3"
+       classpath "com.android.databinding:dataBinder:1.0-rc0"
+   }
 }
+
+

+ Then make sure jcenter is in the repositories list for your sub projects. +

+ +
 allprojects {
    repositories {
        jcenter()
-       maven {
-           url config.mavenRepoDir
-       }
    }
 }
 
+

+ In each module you want to use data binding, apply the plugin right after + android plugin +

-

Next, add the following lines to the build.gradle -file of each module that will use data-binding. The application module must -have this, even if only its libraries use data binding.

- -
-apply plugin: 'com.android.databinding'
-dependencies {
-    compile "com.android.databinding:library:${config.snapshotVersion}"
-    compile "com.android.databinding:baseLibrary:${config.snapshotVersion}"
-    compile "com.android.databinding:adapters:${config.snapshotVersion}"
-    provided "com.android.databinding:annotationprocessor:${config.snapshotVersion}"
-}
+
+apply plugin: ‘com.android.application'
+apply plugin: 'com.android.databinding'
 
+

+ The data binding plugin is going to add necessary provided + and compile configuration dependencies to your project. +

+

+ Data Binding Layout Files +

-

Data Binding Layout Files

- - -

Writing your first data binding expressions:

+

+ 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:

+

+ 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: +

-
-<?xml version="1.0" encoding="utf-8"?>
-<layout xmlns:android="http://schemas.android.com/apk/res/android">
-   <data>
-       <variable name="user" type="com.example.User"/>
-   </data>
+
+<?xml version="1.0" encoding="utf-8"?>
+<layout xmlns:android="http://schemas.android.com/apk/res/android">
+   <data>
+       <variable name="user" type="com.example.User"/>
+   </data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
-       android:layout_height="match_parent">
+       android:layout_height="match_parent">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
-           android:text="@{user.firstName}"/>
+           android:text="@{user.firstName}"/>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
-           android:text="@{user.lastName}"/>
-   </LinearLayout>
-</layout>
+           android:text="@{user.lastName}"/>
+   </LinearLayout>
+</layout>
 
+

+ The user variable within data describes a + property that may be used within this layout. +

-

The user variable within data describes a property that may be used within this layout.

- -
-<variable name="user" type="com.example.User"/>
+
+<variable name="user" type="com.example.User"/>
 
+

+ 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: +

-

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:

-
+
 <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
-          android:text="@{user.firstName}"/>
+          android:text="@{user.firstName}"/>
 
+

+ Data Object +

+

+ Let’s assume for now that you have a plain-old Java object (POJO) for User: +

-

Data Object

- -

Let’s assume for now that you have a plain-old Java object (POJO) for User:

-
+
 public class User {
    public final String firstName;
    public final String lastName;
@@ -125,11 +263,13 @@ be in a non-binding layout file.A sample file looks like this:

} }
+

+ 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: +

-

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:

-
+
 public class User {
    private final String firstName;
    private final String lastName;
@@ -145,18 +285,29 @@ possible to use a JavaBeans objects:

} }
+

+ From the perspective of data binding, these two classes are equivalent. The + expression @{user.firstName} 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. +

-

From the perspective of data binding, these two classes are equivalent. The -expression @{user.lastName} 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. -

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 activity_main.xml so the generate class was ActivityMainBinding. 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: +

+ 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 activity_main.xml so the generate class was + ActivityMainBinding. 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:

-
+
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
@@ -165,242 +316,402 @@ expressions.The easiest means for creating the bindings is to do it while inflat
    binding.setUser(user);
 }
 
+

+ You’re done! Run the application and you’ll see Test User in the UI. + Alternatively, you can get the view via: +

-

You’re done! Run the application and you’ll see Test User in the UI.Alternatively, you can get the view via: -

+
 MainActivityBinding binding = MainActivityBinding.inflate(getLayoutInflater());
 
+

+ If you are using data binding items inside a ListView or RecyclerView + adapter, you may prefer to use: +

-

If you are using data binding items inside a ListView or RecyclerView adapter, -you may prefer to use: -

+
 ListItemBinding binding = ListItemBinding.inflate(layoutInflater, viewGroup,
 false);
 //or
 ListItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false);
 
+

+ 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. +

- -

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. -

-<data>
-    <import type="android.view.View"/>
-</data>
+
+<data>
+    <import type="android.view.View"/>
+</data>
 
+

+ Now, View may be used within your binding expression: +

-

Now, View may be used within your binding expression: -

+
 <TextView
    android:text="@{user.lastName}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
-   android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>
+   android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>
 
+

+ When there are class name conflicts, one of the classes may be renamed to an + “alias:” +

-

When there are class name conflicts, one of the classes may be renamed to an -“alias:”

-
-<import type="android.view.View"/>
+
+<import type="android.view.View"/>
 <import type="com.example.real.estate.View"
-        alias="Vista"/>
+        alias="Vista"/>
 
+

+ 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: +

-

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:

-
-<data>
-    <import type="com.example.User"/>
-    <import type="java.util.List"/>
-    <variable name="user" type="User"/>
-    <variable name="userList" type="List<User>"/>
-</data>
-…
+
+<data>
+    <import type="com.example.User"/>
+    <import type="java.util.List"/>
+    <variable name="user" type="User"/>
+    <variable name="userList" type="List&lt;User>"/>
+    </data>
+
+

+ 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. +

+ +
 <TextView
    android:text="@{((User)(user.connection)).lastName}"
    android:layout_width="wrap_content"
-   android:layout_height="wrap_content"/>
+   android:layout_height="wrap_content"/>
 
+

+ Imported types may also be used when referencing static fields and methods in + expressions: +

-

Imported types may also be used when referencing static fields and methods in -expressions:

-
-<data>
-    <import type="com.example.MyStringUtils"/>
-    <variable name="user" type="com.example.User"/>
-</data>
+
+<data>
+    <import type="com.example.MyStringUtils"/>
+    <variable name="user" type="com.example.User"/>
+</data>
 …
 <TextView
    android:text="@{MyStringUtils.capitalize(user.lastName)}"
    android:layout_width="wrap_content"
-   android:layout_height="wrap_content"/>
+   android:layout_height="wrap_content"/>
 
+

+ Just as in Java, java.lang.* is imported automatically. +

-

Just as in Java, java.lang.* is imported automatically.

-

Variables

+

+ 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.

-
-<data>
-    <import type="android.graphics.drawable.Drawable"/>
-    <variable name="user"  type="com.example.User"/>
-    <variable name="image" type="Drawable"/>
-    <variable name="note"  type="String"/>
-</data>
-
+

+ 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, 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!

+
+<data>
+    <import type="android.graphics.drawable.Drawable"/>
+    <variable name="user"  type="com.example.User"/>
+    <variable name="image" type="Drawable"/>
+    <variable name="note"  type="String"/>
+</data>
+
+

+ 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.

+

+ 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.

+

+ 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

+

+ 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. +

-

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: +

-

Binding classes may be renamed or placed in different packages by adjusting the class attribute of the data element. For example:

-
-<data class="ContactItem">
+
+<data class="ContactItem">
     ...
-</data>
+</data>
 
+

+ 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 + “.”: +

-

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 “.”:

-
-<data class=".ContactItem">
+
+<data class=".ContactItem">
     ...
-</data>
+</data>
 
+

+ In this case, ContactItem is generated in the module package + directly. Any package may be used if the full package is provided: +

-In this case, ContactItem is generated in the module package directly.Any package may be used if the full package is provided: -
-<data class="com.example.ContactItem">
+
+<data class="com.example.ContactItem">
     ...
-</data>
+</data>
 
+

+ 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: +

- -

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:

-
-<?xml version="1.0" encoding="utf-8"?>
+
+<?xml version="1.0" encoding="utf-8"?>
 <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>
+        xmlns:bind="http://schemas.android.com/apk/res-auto">
+   <data>
+       <variable name="user" type="com.example.User"/>
+   </data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
-       android:layout_height="match_parent">
+       android:layout_height="match_parent">
        <include layout="@layout/name"
-           bind:user="@{user}"/>
+           bind:user="@{user}"/>
        <include layout="@layout/contact"
-           bind:user="@{user}"/>
-   </LinearLayout>
-</layout>
+           bind:user="@{user}"/>
+   </LinearLayout>
+</layout>
 
+

+ Here, there must be a user variable in both the + name.xml and contact.xml layout files. +

-

Here, there must be a user variable in both the name.xml and contact.xml layout files.

-

Expression Language

+

+ Expression Language +

+

+ Common Features +

-

Common Features

+

+ The expression language looks a lot like a Java expression. These are the + same: +

-

The expression language looks a lot like a Java expression. These are the same:

    -
  • Mathematical + - / * % -
  • String concatenation + -
  • Logical && || -
  • Binary & | ^ -
  • Unary + - ! ~ -
  • Shift >> >>> << -
  • Comparison == > < >= <= -
  • instanceof -
  • Grouping () -
  • Literals - character, String, numeric, null -
  • Cast -
  • Method calls -
  • Field access -
  • Array access [] -
  • Ternary operator ?: +
  • Mathematical + - / * % +
  • + +
  • String concatenation + +
  • + +
  • + Logical && || +
  • + +
  • Binary & | ^ +
  • + +
  • Unary + - ! ~ +
  • + +
  • Shift >> >>> << +
  • + +
  • Comparison == > < >= <= +
  • + +
  • + instanceof +
  • + +
  • Grouping () +
  • + +
  • Literals - character, String, numeric, null +
  • + +
  • Cast +
  • + +
  • Method calls +
  • + +
  • Field access +
  • + +
  • Array access [] +
  • + +
  • Ternary operator ?: +
-

Examples:

-
+
+

+ Examples: +

+ +
 android:text="@{String.valueOf(index + 1)}"
-android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}"
+android:visibility="@{age &lt; 13 ? View.GONE : View.VISIBLE}"
 android:transitionName='@{"image_" + id}'
 
+

+ Missing Operations +

+

+ A few operations are missing from the expression syntax that you can use in + Java. +

-

Missing Operations

- -

A few operations are missing from the expression syntax that you can use in -Java.

    -
  • this -
  • super -
  • new -
  • Explicit generic invocation +
  • + this +
  • + +
  • + super +
  • + +
  • + new +
  • + +
  • Explicit generic invocation +
-

Null Coalescing Operator

+

+ Null Coalescing Operator +

+ +

+ The null coalescing operator (??) chooses the + left operand if it is not null or the right if it is null. +

-

The null coalescing operator (??) chooses the left operand if it is not null or the right if it is null.

-
+
 android:text="@{user.displayName ?? user.lastName}"
 
+

+ This is functionally equivalent to: +

-

This is functionally equivalent to:

-
+
 android:text="@{user.displayName != null ? user.displayName : user.lastName}"
 
+

+ 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. +

- -

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.

-
+
 android:text="@{user.lastName}"
 
+

+ Avoiding NullPointerException +

+ +

+ Generated data binding code automatically checks for nulls and avoid null + pointer exceptions. For example, in the expression + @{user.name}, if user is null, + user.name will be assigned its default value (null). If you were + referencing user.age, where age is an int, then it + would default to 0. +

+

+ Collections +

-

Collections

+

+ Common collections: arrays, lists, sparse lists, and maps, may be accessed + using the [] operator for convenience. +

-

Common collections: arrays, lists, sparse lists, and maps, may be accessed -using the [] operator for convenience.

-
-<data>
-    <import type="android.util.SparseArray"/>
-    <import type="java.util.Map"/>
-    <import type="java.util.List"/>
-    <variable name="list" type="List<String>"/>
-    <variable name="sparse" type="SparseArray<String>"/>
-    <variable name="map" type="Map<String, String>"/>
-    <variable name="index" type="int"/>
-    <variable name="key" type="String"/>
-</data>
+
+<data>
+    <import type="android.util.SparseArray"/>
+    <import type="java.util.Map"/>
+    <import type="java.util.List"/>
+    <variable name="list" type="List<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>
 …
 android:text="@{list[index]}"
 …
@@ -409,134 +720,204 @@ using the [] operator for convenience.

android:text="@{map[key]}"
+

+ String Literals +

+

+ When using single quotes around the attribute value, it is easy to use double + quotes in the expression: +

-

String Literals

- -

When using single quotes around the attribute value, it is easy to use double -quotes in the expression:

-
+
 android:text='@{map["firstName"]}'
 
+

+ It is also possible to use double quotes to surround the attribute value. + When doing so, String literals should either use the &quot; or back quote + (`). +

-

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 (`).

-
+
 android:text="@{map[`firstName`}"
-android:text="@{map["firstName"]}"
+android:text="@{map[&quot;firstName&quot;]}"
 
+

+ Resources +

+

+ It is possible to access resources as part of expressions using the normal + syntax: +

-

Resources

- -

It is possible to access resources as part of expressions using the normal -syntax:

-
+
 android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"
 
+

+ Format strings and plurals may be evaluated by providing parameters: +

-

Format strings and plurals may be evaluated by providing parameters:

-
+
 android:text="@{@string/nameFormat(firstName, lastName)}"
 android:text="@{@plurals/banana(bananaCount)}"
 
+

+ When a plural takes multiple parameters, all parameters should be passed: +

-

Some resources require explicit type evaluation.

+
+
+  Have an orange
+  Have %d oranges
+
+android:text="&commat{&commatplurals/orange(orangeCount, orangeCount)}"
+
+

+ Some resources require explicit type evaluation. +

- - - - - - - + + + + + + + +
+String[]
+
+ - - + @array + + @stringArray + + + + + int[] + - - + @array + + @intArray + + + + + TypedArray + - - + @array + + @typedArray + + + + + Animator + - - + @animator + + @animator + + + + + StateListAnimator + - - + @animator + + -color int + + +
+@color
+
+ - - + @color + + + + + ColorStateList + + @color + - + @colorStateList + +
TypeNormal ReferenceExpression Reference
-
-String[]
+ Type + + Normal Reference + + Expression Reference +
-@array -@stringArray
-int[]
-@array -@intArray
-TypedArray
-@array -@typedArray
-Animator
-@animator -@animator
-StateListAnimator
-@animator -@stateListAnimator
- + @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, ObservableFields, 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.

+

+ 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, ObservableFields, and + observable collections. +

-

Observable Objects

+

+ 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 android.databinding.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.

+

+ A class implementing android.databinding.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 an Bindable annotation to the getter and notifying in the setter.

+

+ 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. +

-
+
 private static class User extends BaseObservable {
    private String firstName;
    private String lastName;
@@ -558,169 +939,221 @@ is done by assigning an Bindable annotation to the getter and notif
    }
 }
 
+

+ 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. +

-

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 +

-

ObservableFields

+

+ A little work is involved in creating Observable classes, so developers who + want to save time or have few properties may use ObservableFields. + ObservableFields are self-contained observable objects that have a single + field. There are versions for all primitive types and one for reference + types. To use, create a public final field in the data class: +

-

A little work is involved in creating Observable classes, so developers who -want to save time or have few properties may use ObservableFields. -ObservableFields are self-contained observable objects that have a single -field. There are versions for all primitive types and one for reference types. -To use, create a public final field in the data class:

-
+
 private static class User extends BaseObservable {
-   public final ObservableField<String> firstName =
-       new ObservableField<>();
-   public final ObservableField<String> lastName =
-       new ObservableField<>();
+   public final ObservableField<String> firstName =
+       new ObservableField<>();
+   public final ObservableField<String> lastName =
+       new ObservableField<>();
    public final ObservableInt age = new ObservableInt();
 }
 
+

+ That's it! To access the value, use the set and get accessor methods: +

-

That's it! To access the value, use the set and get accessor methods:

-
+
 user.firstName.set("Google");
 int age = user.age.get();
 
+

+ 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. +

- -

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.

- -
-ObservableArrayMap<String, Object> user = new ObservableArrayMap<>();
+
+ObservableArrayMap<String, Object> user = new ObservableArrayMap<>();
 user.put("firstName", "Google");
 user.put("lastName", "Inc.");
 user.put("age", 17);
 
+

+ In the layout, the map may be accessed through the String keys: +

-In the layout, the map may be accessed through the String keys: -
-<data>
-    <import type="android.databinding.ObservableMap"/>
-    <variable name="user" type="ObservableMap<String, Object>"/>
-</data>
+
+<data>
+    <import type="android.databinding.ObservableMap"/>
+    <variable name="user" type="ObservableMap&lt;String, Object>"/>
+</data>
 …
 <TextView
    android:text='@{user["lastName"]}'
    android:layout_width="wrap_content"
-   android:layout_height="wrap_content"/>
+   android:layout_height="wrap_content"/>
 <TextView
    android:text='@{String.valueOf(1 + (Integer)user["age"])}'
    android:layout_width="wrap_content"
-   android:layout_height="wrap_content"/>
+   android:layout_height="wrap_content"/>
 
+

+ ObservableArrayList is useful when the key is an integer: +

-

ObservableArrayList is useful when the key is an integer:

-
-ObservableArrayList<Object> user = new ObservableArrayList<>();
+
+ObservableArrayList<Object> user = new ObservableArrayList<>();
 user.add("Google");
 user.add("Inc.");
 user.add(17);
 
+

+ In the layout, the list may be accessed through the indices: +

-

In the layout, the list may be accessed through the indices:

-
-<data>
-    <import type="android.databinding.ObservableList"/>
-    <import type="com.example.my.app.Fields"/>
-    <variable name="user" type="ObservableList<Object>"/>
-</data>
+
+<data>
+    <import type="android.databinding.ObservableList"/>
+    <import type="com.example.my.app.Fields"/>
+    <variable name="user" type="ObservableList&lt;Object>"/>
+</data>
 …
 <TextView
    android:text='@{user[Fields.LAST_NAME]}'
    android:layout_width="wrap_content"
-   android:layout_height="wrap_content"/>
+   android:layout_height="wrap_content"/>
 <TextView
    android:text='@{String.valueOf(1 + (Integer)user[Fields.AGE])}'
    android:layout_width="wrap_content"
-   android:layout_height="wrap_content"/>
+   android:layout_height="wrap_content"/>
 
+

+ 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 android.databinding.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: +

-

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 android.databinding.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 are versions that attach the View to its parent and that inflate without -attaching.

-
-MyLayoutBinding binding = MyLayoutBinding.inflate(this);
-MyLayoutBinding binding = MyLayoutBinding.inflate(viewGroup);
+
+MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater);
+MyLayoutBinding binding = MyLayoutBinding.inflate(LayoutInflater, viewGroup, false);
 
+

+ If the layout was inflated using a different mechanism, it may be bound + separately: +

-

If the layout was inflated using a different mechanism, it may be bound -separately:

-
+
 MyLayoutBinding binding = MyLayoutBinding.bind(viewRoot);
 
+

+ Sometimes the binding cannot be known in advance. In such cases, the binding + can be created using the DataBindingUtil class: +

-

Sometimes the binding cannot be known in advance. In such cases, the binding -can be created using the DataBindingUtil class:

-
-ViewDataBinding binding = DataBindingUtil.inflate(context, layoutId,
+
+ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater, layoutId,
     parent, attachToParent);
 ViewDataBinding binding = DataBindingUtil.bindTo(viewRoot, layoutId);
 
+

+ 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: +

- -

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:

-
-<layout xmlns:android="http://schemas.android.com/apk/res/android">
-   <data>
-       <variable name="user" type="com.example.User"/>
-   </data>
+
+<layout xmlns:android="http://schemas.android.com/apk/res/android">
+   <data>
+       <variable name="user" type="com.example.User"/>
+   </data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
-       android:layout_height="match_parent">
+       android:layout_height="match_parent">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
-           android:text="@{user.firstName}"
-           android:id="@+id/firstName"/>
+           android:text="@{user.firstName}"
+   android:id="@+id/firstName"/>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
-           android:text="@{user.lastName}"           android:id="@+id/lastName"/>
-   </LinearLayout>
-</layout>
+           android:text="@{user.lastName}"
+  android:id="@+id/lastName"/>
+   </LinearLayout>
+</layout>
 
+

+ Will generate a binding class with: +

-Will generate a binding class with: -
+
 public final TextView firstName;
 public final TextView lastName;
 
+

+ 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 +

-

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. +

-

Each variable will be given a accessor methods.

-
-<data>
-    <import type="android.graphics.drawable.Drawable"/>
-    <variable name="user"  type="com.example.User"/>
-    <variable name="image" type="Drawable"/>
-    <variable name="note"  type="String"/>
-</data>
+
+<data>
+    <import type="android.graphics.drawable.Drawable"/>
+    <variable name="user"  type="com.example.User"/>
+    <variable name="image" type="Drawable"/>
+    <variable name="note"  type="String"/>
+</data>
 
+

+ will generate setters and getters in the binding: +

-

will generate setters and getters in the binding:

-
+
 public abstract com.example.User getUser();
 public abstract void setUser(com.example.User user);
 public abstract Drawable getImage();
@@ -728,103 +1161,160 @@ some instances where access to Views are still necessary from code.

public abstract String getNote(); public abstract void setNote(String note);
+

+ ViewStubs +

+ +

+ ViewStubs 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. +

-

ViewStubs

- -

ViewStubs 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 -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.

+

+ When inflating another layout, a binding must be established for the new + layout. Therefore, the ViewStubProxy must listen to the ViewStub's + 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

+

+ Advanced Binding +

+

+ Dynamic Variables +

-

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. +

-

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.

+

+ In this example, all layouts that the RecyclerView binds to have an "item" + variable. The BindingHolder has a getBinding method returning the + ViewDataBinding base. +

-

In this example, all layouts that the RecyclerView binds to have an "item" -variable. The BindingHolder has a getBinding method returning the ViewDataBinding base.

-
+
 public void onBindViewHolder(BindingHolder holder, int position) {
    final T item = mItems.get(position);
    holder.getBinding().setVariable(BR.item, item);
    holder.getBinding().executePendingBindings();
 }
 
+

+ 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 +

-

Immediate Binding

+

+ 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. +

-

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.

-

Attribute Setters

+

+ 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

+

+ 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 an attribute, data binding tries to find the method setAttribute. The namespace for the attribute does not matter, only the attribute name itself. +

+ 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. +

-

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.

-
+
 <android.support.v4.widget.DrawerLayout
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     app:scrimColor="@{@color/scrim}"
-    app:drawerListener="@{fragment.drawerListener}"/>
+    app:drawerListener="@{fragment.drawerListener}"/>
 
+

+ 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, not setTint. +

- -

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, not setTint.

-
+
 @BindingMethods({
        @BindingMethod(type = "android.widget.ImageView",
                       attribute = "android:tint",
                       method = "setImageTintList"),
 })
 
+

+ It is unlikely that developers will need to rename setters; the android + framework attributes have already been implemented. +

-

It is unlikely that developers will need to rename setters; the android -framework attributes have already been implemented.

-

Custom Setters

+

+ 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 BindingAdapters created. + For example, here is the one for paddingLeft: +

-

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 BindingAdapters created. For example, -here is the one for paddingLeft:

-

@BindingAdapter("android:paddingLeft") public static void setPaddingLeft(View view, int padding) { view.setPadding(padding, @@ -833,76 +1323,113 @@ here is the one for paddingLeft:

view.getPaddingBottom()); }
+

+ Binding adapters are useful for other types of customization. For example, a + custom loader can be called off-thread to load an image. +

-

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. +

-

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. +

-

You can also have adapters that receive multiple parameters.

-
-@BindingAdapter(attributes = {"bind:imageUrl", "bind:error"})
+
+@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=“@{venue.imageUrl}”
+app:error=“@{@drawable/venueError}”/>
+
+ +

+ 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. +

-

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 ignore during matching. -
  • You can also write adapters for android namespace. -
+
  • Custom namespaces are ignored during matching. +
  • -
    -<ImageView app:imageUrl=“@{venue.imageUrl}”
    -app:error=“@{@drawable/venueError}”/>
    -
    +
  • You can also write adapters for android namespace. +
  • + +

    + Converters +

    -

    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. +

    -

    Object Conversions

    +

    + This is a convenience for those using ObservableMaps to hold data. for + example: +

    -

    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:

    -
    +
     <TextView
        android:text='@{userMap["lastName"]}'
        android:layout_width="wrap_content"
    -   android:layout_height="wrap_content"/>
    +   android:layout_height="wrap_content"/>
     
    -

    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

    +

    +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:

    -
    +

    + Sometimes conversions should be automatic between specific types. For + example, when setting the background: +

    + +
     <View
        android:background="@{isError ? @color/red : @color/white}"
        android:layout_width="wrap_content"
    -   android:layout_height="wrap_content"/>
    +   android:layout_height="wrap_content"/>
     
    +

    + 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: +

    -

    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:

    -
    +
     @BindingConversion
     public static ColorDrawable convertColorToDrawable(int color) {
        return new ColorDrawable(color);
     }
     
    +

    + Note that conversions only happen at the setter level, so it is not + allowed to mix types like this: +

    -

    Note that conversions only happen at the setter level, so it is not allowed to mix types like this:

    -
    +
     <View
        android:background="@{isError ? @drawable/error : @color/white}"
        android:layout_width="wrap_content"
    -   android:layout_height="wrap_content"/>
    +   android:layout_height="wrap_content"/>
     
    - diff --git a/docs/html/tools/data-binding/index.jd b/docs/html/tools/data-binding/index.jd index ae5295a..4ad11b6 100644 --- a/docs/html/tools/data-binding/index.jd +++ b/docs/html/tools/data-binding/index.jd @@ -1,7 +1,5 @@ page.title=Android Data Binding Library -page.metaDescription=Engaging and retaining active users are the keys to success. Here are some resources to help you build an active user base. -section.landing=true -nonavpage=true +page.metaDescription= @jd:body diff --git a/docs/html/tools/tools_toc.cs b/docs/html/tools/tools_toc.cs index 2f96570..f46dcaa 100644 --- a/docs/html/tools/tools_toc.cs +++ b/docs/html/tools/tools_toc.cs @@ -298,7 +298,6 @@ class="en">Support Library
    -- cgit v1.1