`
yhz61010
  • 浏览: 566863 次
  • 来自: -
博客专栏
63c13ecc-ef01-31cf-984e-de461c7dfde8
libgdx 游戏开发
浏览量:12339
社区版块
存档分类
最新评论

了解数据绑定 - Data Binding Library

阅读更多

原文地址:https://developer.android.com/topic/libraries/data-binding/index.html

 

Data Binding Library

 

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 compatibility — 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.5.0-alpha1 or higher is required. See how to update the Android Plugin for Gradle.

Build Environment


To get started with Data Binding, download the library from the Support repository in the Android SDK manager.

To configure your app to use data binding, add the dataBindingelement to your build.gradle file in the app module.

Use the following code snippet to configure data binding:

android {
    ....
    dataBinding {
        enabled =true
    }
}

If you have an app module that depends on a library which uses data binding, your app module must configure data binding in its build.gradle file as well.

Also, make sure you are using a compatible version of Android Studio.Android Studio 1.3 and later provides support for data binding as described in Android Studio Support for Data Binding.

Data Binding Layout Files


Writing your first set of data binding expressions

Data-binding layout files are slightly different and start with a root tag of layout followed by a data element and aview 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"?>
<layoutxmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variablename="user"type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextViewandroid:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"/>
       <TextViewandroid:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.lastName}"/>
   </LinearLayout>
</layout>

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

<variablename="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:

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

Data Object

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

publicclassUser{
   publicfinalString firstName;
   publicfinalString lastName;
   publicUser(String firstName,String lastName){
       this.firstName = firstName;
       this.lastName = lastName;
   }
}

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:

publicclassUser{
   privatefinalString firstName;
   privatefinalString lastName;
   publicUser(String firstName,String lastName){
       this.firstName = firstName;
       this.lastName = lastName;
   }
   publicString getFirstName(){
       returnthis.firstName;
   }
   publicString getLastName(){
       returnthis.lastName;
   }
}

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. 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 wasMainActivityBinding. 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
protectedvoid onCreate(Bundle savedInstanceState){
   super.onCreate(savedInstanceState);
   MainActivityBinding binding =DataBindingUtil.setContentView(this, R.layout.main_activity);
   User user =newUser("Test","User");
   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:

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

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);

Event Handling

Data Binding allows you to write expressions handling events that are dispatched from the views (e.g. onClick). 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. There are two ways to handle an event.

  • Method References: In your expressions, you can reference methods that conform to the signature of the listener method. When an expression evaluates to a method reference, Data Binding wraps the method reference and owner object in a listener, and sets that listener on the target view. If the expression evaluates to null, Data Binding does not create a listener and sets a null listener instead.
  • Listener Bindings: These are lambda expressions that are evaluated when the event happens. Data Binding always creates a listener, which it sets on the view. When the event is dispatched, the listener evaluates the lambda expression.

Method References

Events can be bound to handler methods directly, similar to the way android:onClick can be assigned to a method in an Activity. One major advantage compared to the View#onClick attribute is that the expression is processed at compile time, so if the method does not exist or its signature is not correct, you receive a compile time error.

The major difference between Method References and Listener Bindings is that the actual listener implementation is created when the data is bound, not when the event is triggered. If you prefer to evaluate the expression when the event happens, you should use listener binding.

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:

publicclassMyHandlers{
    publicvoid onClickFriend(View view){...}
}

The binding expression can assign the click listener for a View:

<?xml version="1.0" encoding="utf-8"?>
<layoutxmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variablename="handlers"type="com.example.Handlers"/>
       <variablename="user"type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextViewandroid:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"
           android:onClick="@{handlers::onClickFriend}"/>
   </LinearLayout>
</layout>

Note that the signature of the method in the expression must exactly match the signature of the method in the Listener object.

Listener Bindings

Listener Bindings are binding expressions that run when an event happens. They are similar to method references, but they let you run arbitrary data binding expressions. This feature is available with Android Gradle Plugin for Gradle version 2.0 and later.

In method references, the parameters of the method must match the parameters of the event listener. In Listener Bindings, only your return value must match the expected return value of the listener (unless it is expecting void). For example, you can have a presenter class that has the following method:

publicclassPresenter{
    publicvoid onSaveClick(Task task){}
}
Then you can bind the click event to your class as follows:
  <?xml version="1.0" encoding="utf-8"?>
  <layoutxmlns:android="http://schemas.android.com/apk/res/android">
      <data>
          <variablename="task"type="com.android.example.Task"/>
          <variablename="presenter"type="com.android.example.Presenter"/>
      </data>
      <LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent">
          <Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"
          android:onClick="@{() -> presenter.onSaveClick(task)}" />
      </LinearLayout>
  </layout>

Listeners are represented by lambda expressions that are allowed only as root elements of your expressions. When a callback is used in an expression, Data Binding automatically creates the necessary listener and registers for the event. When the view fires the event, Data Binding evaluates the given expression. As in regular binding expressions, you still get the null and thread safety of Data Binding while these listener expressions are being evaluated.

Note that in the example above, we haven't defined the view parameter that is passed into onClick(android.view.View). Listener bindings provide two choices for listener parameters: you can either ignore all parameters to the method or name all of them. If you prefer to name the parameters, you can use them in your expression. For example, the expression above could be written as:

  android:onClick="@{(view) -> presenter.onSaveClick(task)}"
Or if you wanted to use the parameter in the expression, it could work as follows:
publicclassPresenter{
    publicvoid onSaveClick(View view,Task task){}
}
  android:onClick="@{(theView) -> presenter.onSaveClick(theView, task)}"
You can use a lambda expression with more than one parameter:
publicclassPresenter{
    publicvoid onCompletedChanged(Task task,boolean completed){}
}
  <CheckBoxandroid:layout_width="wrap_content"android:layout_height="wrap_content"
        android:onCheckedChanged="@{(cb, isChecked) -> presenter.completeChanged(task, isChecked)}" />

If the event you are listening to returns a value whose type is not void, your expressions must return the same type of value as well. For example, if you want to listen for the long click event, your expression should return boolean.

publicclassPresenter{
    publicboolean onLongClick(View view,Task task){}
}
  android:onLongClick="@{(theView) -> presenter.onLongClick(theView, task)}"

If the expression cannot be evaluated due to null objects, Data Binding returns the default Java value for that type. For example, null for reference types, 0 for intfalse for boolean, etc.

If you need to use an expression with a predicate (e.g. ternary), you can use void as a symbol.

  android:onClick="@{(v) -> v.isVisible() ? doSomething() : void}"
Avoid Complex Listeners
Listener expressions are very powerful and can make your code very easy to read. On the other hand, listeners containing complex expressions make your layouts hard to read and unmaintainable. These expressions should be as simple as passing available data from your UI to your callback method. You should implement any business logic inside the callback method that you invoked from the listener expression.

Some specialized click event handlers exist and they need an attribute other than android:onClick to avoid a conflict. The following attributes have been created to avoid such conflicts:

Class Listener Setter Attribute
SearchView setOnSearchClickListener(View.OnClickListener) android:onSearchClick
ZoomControls setOnZoomInClickListener(View.OnClickListener) android:onZoomIn
ZoomControls setOnZoomOutClickListener(View.OnClickListener) android:onZoomOut

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>
    <importtype="android.view.View"/>
</data>

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}"/>

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

<importtype="android.view.View"/>
<importtype="com.example.real.estate.View"
        alias="Vista"/>

Now, Vista may be used to reference the com.example.real.estate.View and View may be used to referenceandroid.view.View within the layout file. Imported types may be used as type references in variables and expressions:

<data>
    <importtype="com.example.User"/>
    <importtype="java.util.List"/>
    <variablename="user"type="User"/>
    <variablename="userList"type="List&lt;User&gt;"/>
</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"/>

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

<data>
    <importtype="com.example.MyStringUtils"/>
    <variablename="user"type="com.example.User"/>
</data><TextView
   android:text="@{MyStringUtils.capitalize(user.lastName)}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>

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.

<data>
    <importtype="android.graphics.drawable.Drawable"/>
    <variablename="user"  type="com.example.User"/>
    <variablename="image"type="Drawable"/>
    <variablename="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.

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 intfalse for boolean, etc.

A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name.

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 generateContactItemBinding. If the module package is com.example.my.app, then it will be placed incom.example.my.app.databinding.

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

<dataclass="ContactItem">
    ...
</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 ".":

<dataclass=".ContactItem">
    ...
</data>

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

<dataclass="com.example.ContactItem">
    ...
</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:

<?xml version="1.0" encoding="utf-8"?>
<layoutxmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:bind="http://schemas.android.com/apk/res-auto">
   <data>
       <variablename="user"type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <includelayout="@layout/name"
           bind:user="@{user}"/>
       <includelayout="@layout/contact"
           bind:user="@{user}"/>
   </LinearLayout>
</layout>

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:

<?xml version="1.0" encoding="utf-8"?>
<layoutxmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:bind="http://schemas.android.com/apk/res-auto">
   <data>
       <variablename="user"type="com.example.User"/>
   </data>
   <merge>
       <includelayout="@layout/name"
           bind:user="@{user}"/>
       <includelayout="@layout/contact"
           bind:user="@{user}"/>
   </merge>
</layout>

Expression Language

Common Features

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

Examples:

android:text="@{String.valueOf(index + 1)}"
android:visibility="@{age < 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.

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

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

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.

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

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

<data>
    <importtype="android.util.SparseArray"/>
    <importtype="java.util.Map"/>
    <importtype="java.util.List"/>
    <variablename="list"type="List&lt;String&gt;"/>
    <variablename="sparse"type="SparseArray&lt;String&gt;"/>
    <variablename="map"type="Map&lt;String, String&gt;"/>
    <variablename="index"type="int"/>
    <variablename="key"type="String"/>
</data>
…
android:text="@{list[index]}"
…
android:text="@{sparse[index]}"
…
android:text="@{map[key]}"

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 ' or back quote (`).

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

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:

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

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


  Have an orange
  Have%d oranges

android:text="@{@plurals/orange(orangeCount, orangeCount)}"

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 objectsobservable fields, andobservable 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.

privatestaticclassUserextendsBaseObservable{
   privateString firstName;
   privateString lastName;
   @Bindable
   publicString getFirstName(){
       returnthis.firstName;
   }
   @Bindable
   publicString getLastName(){
       returnthis.lastName;
   }
   publicvoid setFirstName(String firstName){
       this.firstName = firstName;
       notifyPropertyChanged(BR.firstName);
   }
   publicvoid setLastName(String lastName){
       this.lastName = lastName;
       notifyPropertyChanged(BR.lastName);
   }
}

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 ObservableBooleanObservableByteObservableChar,ObservableShortObservableIntObservableLongObservableFloatObservableDouble, andObservableParcelableObservableFields 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:

privatestaticclassUser{
   publicfinalObservableField<String> firstName =
       newObservableField<>();
   publicfinalObservableField<String> lastName =
       newObservableField<>();
   publicfinalObservableInt age =newObservableInt();
}

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.

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

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

<data>
    <importtype="android.databinding.ObservableMap"/>
    <variablename="user"type="ObservableMap&lt;String, Object&gt;"/>
</data><TextView
   android:text='@{user["lastName"]}'
   android:layout_width="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"/>

ObservableArrayList is useful when the key is an integer:

ObservableArrayList<Object> user =newObservableArrayList<>();
user.add("Google");
user.add("Inc.");
user.add(17);

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

<data>
    <importtype="android.databinding.ObservableList"/>
    <importtype="com.example.my.app.Fields"/>
    <variablename="user"type="ObservableList&lt;Object&gt;"/>
</data><TextView
   android:text='@{user[Fields.LAST_NAME]}'
   android:layout_width="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"/>

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:

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:

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:

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:

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

Will generate a binding class with:

publicfinalTextView firstName;
publicfinalTextView 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

Each variable will be given accessor methods.

<data>
    <importtype="android.graphics.drawable.Drawable"/>
    <variablename="user"  type="com.example.User"/>
    <variablename="image"type="Drawable"/>
    <variablename="note"  type="String"/>
</data>

will generate setters and getters in the binding:

publicabstract com.example.User getUser();
publicabstractvoid setUser(com.example.User user);
publicabstractDrawable getImage();
publicabstractvoid setImage(Drawable image);
publicabstractString getNote();
publicabstractvoid 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 theViewStub, 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 ViewStubProxymust 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 theonBindViewHolder(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.

publicvoid 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 theexecutePendingBindings() 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 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.

<android.support.v4.widget.DrawerLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:scrimColor="@{@color/scrim}"
    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 BindingMethodannotations, one for each renamed method. For example, the android:tint attribute is really associated with setImageTintList(ColorStateList), 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.

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:

@BindingAdapter("android:paddingLeft")
publicstaticvoid setPaddingLeft(View view,int padding){
   view.setPadding(padding,
                   view.getPaddingTop(),
                   view.getPaddingRight(),
                   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.

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.

@BindingAdapter({"bind:imageUrl","bind:error"})
publicstaticvoid loadImage(ImageView view,String url,Drawable error){
   Picasso.with(view.getContext()).load(url).error(error).into(view);
}
<ImageViewapp: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.

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

@BindingAdapter("android:paddingLeft")
publicstaticvoid setPaddingLeft(View view,int oldPadding,int newPadding){
   if(oldPadding != newPadding){
       view.setPadding(newPadding,
                       view.getPaddingTop(),
                       view.getPaddingRight(),
                       view.getPaddingBottom());
   }
}

Event handlers may only be used with interfaces or abstract classes with one abstract method. For example:

@BindingAdapter("android:onLayoutChange")
publicstaticvoid setOnLayoutChangeListener(View view,View.OnLayoutChangeListener oldValue,
       View.OnLayoutChangeListener newValue){
    if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB){
        if(oldValue !=null){
            view.removeOnLayoutChangeListener(oldValue);
        }
        if(newValue !=null){
            view.addOnLayoutChangeListener(newValue);
        }
    }
}

When a listener has multiple methods, it must be split into multiple listeners. For example,View.OnAttachStateChangeListener has two methods: onViewAttachedToWindow() andonViewDetachedFromWindow(). We must then create two interfaces to differentiate the attributes and handlers for them.

@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
publicinterfaceOnViewDetachedFromWindow{
    void onViewDetachedFromWindow(View v);
}

@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
publicinterfaceOnViewAttachedToWindow{
    void onViewAttachedToWindow(View v);
}

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.

@BindingAdapter("android:onViewAttachedToWindow")
publicstaticvoid setListener(View view,OnViewAttachedToWindow attached){
    setListener(view,null, attached);
}

@BindingAdapter("android:onViewDetachedFromWindow")
publicstaticvoid setListener(View view,OnViewDetachedFromWindow detached){
    setListener(view, detached,null);
}

@BindingAdapter({"android:onViewDetachedFromWindow","android:onViewAttachedToWindow"})
publicstaticvoid setListener(View view,finalOnViewDetachedFromWindow detach,
        finalOnViewAttachedToWindow attach){
    if(VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1){
        finalOnAttachStateChangeListener newListener;
        if(detach ==null&& attach ==null){
            newListener =null;
        }else{
            newListener =newOnAttachStateChangeListener(){
                @Override
                publicvoid onViewAttachedToWindow(View v){
                    if(attach !=null){
                        attach.onViewAttachedToWindow(v);
                    }
                }

                @Override
                publicvoid onViewDetachedFromWindow(View v){
                    if(detach !=null){
                        detach.onViewDetachedFromWindow(v);
                    }
                }
            };
        }
        finalOnAttachStateChangeListener oldListener =ListenerUtil.trackListener(view,
                newListener, R.id.onAttachStateChangeListener);
        if(oldListener !=null){
            view.removeOnAttachStateChangeListener(oldListener);
        }
        if(newListener !=null){
            view.addOnAttachStateChangeListener(newListener);
        }
    }
}

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 byaddOnAttachStateChangeListener(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:

<TextView
   android:text='@{userMap["lastName"]}'
   android:layout_width="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

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"/>

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
publicstaticColorDrawable convertColorToDrawable(int color){
   returnnewColorDrawable(color);
}

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 Studio Support for Data Binding

Android Studio supports many of the code editing features for data binding code. For example, it supports the following features for data binding expressions:

  • Syntax highlighting
  • Flagging of expression language syntax errors
  • XML code completion
  • References, including navigation (such as navigate to a declaration) and quick documentation

Note: Arrays and a generic type, such as the Observable class, might display errors when there are no errors.

The Preview pane displays default values for data binding expressions if provided. In the following example excerpt of an element from a layout XML file, the Preview pane displays the PLACEHOLDER default text value in the TextView.

<TextViewandroid:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@{user.firstName, default=PLACEHOLDER}"/>

If you need to display a default value during the design phase of your project, you can also use tools attributes instead of default expression values, as described in Designtime Layout Attributes.

分享到:
评论

相关推荐

    ibus-table-chinese-erbi-1.4.6-3.el7.x64-86.rpm.tar.gz

    1、文件内容:ibus-table-chinese-erbi-1.4.6-3.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/ibus-table-chinese-erbi-1.4.6-3.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊

    基于微信小程序的新乡学院自习室预约系统.zip

    选择Java后台技术和MySQL数据库,在前台界面为提升用户体验,使用Jquery、Ajax、CSS等技术进行布局。 系统包括两类用户:学生、管理员。 学生用户只要实现了前台信息的查看,打开首页,查看网站介绍、自习室信息、在线留言、轮播图信息公告等,通过点击首页的菜单跳转到对应的功能页面菜单,包括网站首页、自习室信息、注册登录、个人中心、后台登录。 学生用户通过账户账号登录,登录后具有所有的操作权限,如果没有登录,不能在线预约。学生用户退出系统将注销个人的登录信息。 管理员通过后台的登录页面,选择管理员权限后进行登录,管理员的权限包括轮播公告管理、老师学生信息管理和信息审核管理,管理员管理后点击退出,注销登录信息。 管理员用户具有在线交流的管理,自习室信息管理、自习室预约管理。 在线交流是对前台用户留言内容进行管理,删除留言信息,查看留言信息。

    面向基层就业个性化大学生服务平台(源码+数据库+论文+ppt)java开发springboot框架javaweb,可做计算机毕业设计或课程设计

    面向基层就业个性化大学生服务平台(源码+数据库+论文+ppt)java开发springboot框架javaweb,可做计算机毕业设计或课程设计 【功能需求】 面向基层就业个性化大学生服务平台(源码+数据库+论文+ppt)java开发springboot框架javaweb,可做计算机毕业设计或课程设计 面向基层就业个性化大学生服务平台中的管理员角色主要负责了如下功能操作。 (1)职业分类管理功能需求:对职业进行划分分类管理等。 (2)用户管理功能需求:对用户信息进行维护管理等。 (3)职业信息管理功能需求:对职业信息进行发布等。 (4)问卷信息管理功能需求:可以发布学生的问卷调查操作。 (5)个性化测试管理功能需求:可以发布个性化测试试题。 (6)试题管理功能需求:对测试试题进行增删改查操作。 (7)社区交流管理功能需求:对用户的交流论坛信息进行维护管理。 面向基层就业个性化大学生服务平台中的用户角色主要负责了如下功能操作。 (1)注册登录功能需求:没有账号的用户,可以输入账号,密码,昵称,邮箱等信息进行注册操作,注册后可以输入账号和密码进行登录。 (2)职业信息功能需求:用户可以对职业信息进行查看。 (3)问卷信息功能需求:可以在线进行问卷调查答卷操作。 (4)社区交流功能需求:可以在线进行社区交流。 (5)个性化测试功能需求:可以在线进行个性化测试。 (6)公告资讯功能需求:可以查看浏览系统发布的公告资讯信息。 【环境需要】 1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。 2.IDE环境:IDEA,Eclipse,Myeclipse都可以。 3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可 4.数据库:MySql 5.7/8.0等版本均可; 【购买须知】 本源码项目经过严格的调试,项目已确保无误,可直接用于课程实训或毕业设计提交。里面都有配套的运行环境软件,讲解视频,部署视频教程,一应俱全,可以自己按照教程导入运行。附有论文参考,使学习者能够快速掌握系统设计和实现的核心技术。

    三菱Fx3u程序:自动检测包装机电机控制模板,PLC脉冲与伺服定位,手自动切换功能,三菱Fx3u程序:自动检测包装机电机控制模板-涵盖伺服定位与手自动切换功能,三菱Fx3u程序,自动检测包装机 该

    三菱Fx3u程序:自动检测包装机电机控制模板,PLC脉冲与伺服定位,手自动切换功能,三菱Fx3u程序:自动检测包装机电机控制模板——涵盖伺服定位与手自动切换功能,三菱Fx3u程序,自动检测包装机。 该程序六个电机,plc本体脉冲控制3个轴,3个1pg控制。 程序内包括伺服定位,手自动切,功能快的使用,可作为模板程序,很适合新手。 ,三菱Fx3u程序; 自动检测包装机; 六个电机; PLC脉冲控制; 伺服定位; 手自动切换; 功能快捷键; 模板程序。,三菱Fx3u PLC控制下的自动包装机程序:六电机伺服定位与手自动切换模板程序

    基于多尺度集成极限学习机回归 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    计及信息间隙决策与多能转换的综合能源系统优化调度模型:实现碳经济最大化与源荷不确定性考量,基于信息间隙决策与多能转换的综合能源系统优化调度模型:源荷不确定性下的高效碳经济调度策略,计及信息间隙决策及多

    计及信息间隙决策与多能转换的综合能源系统优化调度模型:实现碳经济最大化与源荷不确定性考量,基于信息间隙决策与多能转换的综合能源系统优化调度模型:源荷不确定性下的高效碳经济调度策略,计及信息间隙决策及多能转的综合能源系统优化调度 本代码构建了含风电、光伏、光热发电系统、燃气轮机、燃气锅炉、电锅炉、储气、储电、储碳、碳捕集装置的综合能源系统优化调度模型,并考虑P2G装置与碳捕集装置联合运行,从而实现碳经济的最大化,最重要的是本文引入了信息间隙决策理论考虑了源荷的不确定性(本代码的重点)与店铺的47代码形成鲜明的对比,注意擦亮眼睛,认准原创,该代码非常适合修改创新,,提供相关的模型资料 ,计及信息间隙决策; 综合能源系统; 优化调度; 多能转换; 碳经济最大化; 风电; 光伏; 燃气轮机; 储气; 储电; 储碳; 碳捕集装置; P2G装置联合运行; 模型资料,综合能源系统优化调度模型:基于信息间隙决策和多能转换的原创方案

    IPG QCW激光模块电源驱动电路设计与实现:包含安全回路、紧急放电回路及光纤互锁功能的多版本原理图解析,IPG QCW激光模块电源驱动电路设计与实现:含安全回路、紧急放电及光纤互锁等多重保护功能的原

    IPG QCW激光模块电源驱动电路设计与实现:包含安全回路、紧急放电回路及光纤互锁功能的多版本原理图解析,IPG QCW激光模块电源驱动电路设计与实现:含安全回路、紧急放电及光纤互锁等多重保护功能的原理图解析,IPG QCW激光模块电源驱动电路, 包含安全回路,紧急放电回路,光纤互锁回路等, 元件参数请根据实际设计适当调整,此电路仅供参考,不提供pcb文件 原理图提供PDF和KICAD两个版本。 ,IPG激光模块; QCW激光电源驱动; 安全回路; 紧急放电回路; 光纤互锁回路; 原理图PDF和KICAD版本。,IPG激光模块电源驱动电路图解:含安全与紧急放电回路

    基于LSSVM的短期电力负荷预测模型及其性能评估:结果揭露精确度与误差分析,LSSVM在短期电力负荷预测中的结果分析:基于均方根误差、平均绝对误差及平均相对百分误差的评估 ,LSSVM最小二乘支持向量

    基于LSSVM的短期电力负荷预测模型及其性能评估:结果揭露精确度与误差分析,LSSVM在短期电力负荷预测中的结果分析:基于均方根误差、平均绝对误差及平均相对百分误差的评估。,LSSVM最小二乘支持向量机做短期电力负荷预测。 结果分析 均方根误差(RMSE):0.79172 平均绝对误差(MAE):0.4871 平均相对百分误差(MAPE):13.079% ,LSSVM(最小二乘支持向量机);短期电力负荷预测;均方根误差(RMSE);平均绝对误差(MAE);平均相对百分误差(MAPE),LSSVM在电力负荷短期预测中的应用及性能分析

    libmtp-examples-1.1.14-1.el7.x64-86.rpm.tar.gz

    1、文件内容:libmtp-examples-1.1.14-1.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/libmtp-examples-1.1.14-1.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊

    《基于 Transformer 的光学字符识别模型》(毕业设计,源码,教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是均来自个人的课程设计、毕业设计或者具体项目,代码都测试ok,都是运行成功后才上传资源,答辩评审绝对信服的,拿来就能用。放心下载使用!源码、说明、论文、数据集一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 4、如有侵权请私信博主,感谢支持

    2023-04-06-项目笔记 - 第四百一十六阶段 - 4.4.2.414全局变量的作用域-414 -2025.02.21

    2023-04-06-项目笔记-第四百一十六阶段-课前小分享_小分享1.坚持提交gitee 小分享2.作业中提交代码 小分享3.写代码注意代码风格 4.3.1变量的使用 4.4变量的作用域与生命周期 4.4.1局部变量的作用域 4.4.2全局变量的作用域 4.4.2.1全局变量的作用域_1 4.4.2.414局变量的作用域_414- 2025-02-21

    MINIST数据集和春风机器学习框架

    MINIST数据集和春风机器学习框架

    ibus-table-chinese-wu-1.4.6-3.el7.x64-86.rpm.tar.gz

    1、文件内容:ibus-table-chinese-wu-1.4.6-3.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/ibus-table-chinese-wu-1.4.6-3.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊

    宿舍管理系统(源码+数据库+论文+ppt)java开发springboot框架javaweb,可做计算机毕业设计或课程设计

    宿舍管理系统(源码+数据库+论文+ppt)java开发springboot框架javaweb,可做计算机毕业设计或课程设计 【功能需求】 系统拥有管理员和学生两个角色,主要具备系统首页、个人中心、学生管理、宿舍信息管理、宿舍分配管理、水电费管理、进入宿舍管理、出入宿舍管理、维修信息管理、卫生信息管理、考勤信息管理、留言板、交流论坛、系统管理等功能模块。 【环境需要】 1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。 2.IDE环境:IDEA,Eclipse,Myeclipse都可以。 3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可 4.数据库:MySql 5.7/8.0等版本均可; 【购买须知】 本源码项目经过严格的调试,项目已确保无误,可直接用于课程实训或毕业设计提交。里面都有配套的运行环境软件,讲解视频,部署视频教程,一应俱全,可以自己按照教程导入运行。附有论文参考,使学习者能够快速掌握系统设计和实现的核心技术。

    基于智能算法的无人机路径规划研究 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    人凤飞飞凤飞飞是粉色丰富

    人凤飞飞凤飞飞是粉色丰富

    2024蓝桥杯嵌入式学习资料

    2024蓝桥杯嵌入式学习资料

    image_download_1740129191509.jpg

    image_download_1740129191509.jpg

    基于Multisim仿真的带优先病房呼叫系统设计(仿真图)

    基于Multisim仿真的带优先病房呼叫系统设计(仿真图) 设计一个病房呼叫系统。 功能 (1)当有病人紧急呼叫时,产生声,光提示,并显示病人的编号; (2)根据病人的病情设计优先级别,当有多人呼叫时,病情严重者优先; (3)医护人员处理完当前最高级别的呼叫后,系统按优先级别显示其他呼叫病人的病号。

    基于STM32F103的3.6kW全桥逆变器资料:并网充电放电、智能切换与全方位保护方案,基于STM32F103的3.6kW全桥逆变器资料:并网充电放电、智能控制与全方位保护方案,逆变器光伏逆变器,3

    基于STM32F103的3.6kW全桥逆变器资料:并网充电放电、智能切换与全方位保护方案,基于STM32F103的3.6kW全桥逆变器资料:并网充电放电、智能控制与全方位保护方案,逆变器光伏逆变器,3.6kw储能逆变器全套资料 STM32储能逆变器 BOOST 全桥 基于STM32F103设计,具有并网充电、放电;并网离网自动切;485通讯,在线升级;风扇智能控制,提供过流、过压、短路、过温等全方位保护。 基于arm的方案区别于dsp。 有PCB、原理图及代码ad文件。 ,逆变器; 储能逆变器; STM32F103; 3.6kw; 485通讯; 全方位保护; 智能控制; 方案区别; PCB文件; 原理图文件; ad文件。,基于STM32F103的3.6kw储能逆变器:全方位保护与智能控制

Global site tag (gtag.js) - Google Analytics