Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Data Binding library to declare layouts files

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you a detailed introduction of "how to use the Data Binding library to declare layouts files", the content is detailed, the steps are clear, the details are handled properly, I hope this "how to use the Data Binding library to declare layouts files" article can help you solve your doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.

1. Introduction

The Data Binding library is not only flexible but also widely compatible-it is a support library, so you can use it on Android 2.1 (API level 7 +) on all Android platforms.

Required: Android Studio 1.3.0-beta1 or later.

Test version

Please note that the Data Binding library is currently in beta. When Data Binding is in the testing phase, developers should be aware of the following considerations:

This is a test version designed to generate feedback from developers. It may contain bugs, or it may not be suitable for your use case, so you need to use it at your own risk. Even so, we very much hope to get your feedback! Use issue tracker to let us know what works or doesn't work for your use case.

The test version of the Data Binding library tends to change significantly, including source code that is not compatible with your application. That is, there may be a lot of rework to update the library in the future.

Although accompanied by standard Android SDK and Google Play terms of service applicable warnings, developers can release applications built in with the beta version of the Data Binding library at any time. And it's a pretty good idea to test your application thoroughly with new libraries or tools.

We are just beginning to support Android Studio at this time. There will be further Android Studio support in the future.

By using the beta version of the Data Binding library, you acknowledge these warnings.

two。 Build the environment

To start using Data Binding, you first need to download the library in Android SDK Manager's support library.

Make sure you are using a compatible version of Android Studio. The Data Binding plug-in for Android Studio requires Android Studio 1.3.0-beta1 or later.

Working environment

To use Data Binding for your app, you need to add Data Binding to the gradle build file, as follows:

Dependencies {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, as follows:

Allprojects {repositories {jcenter ()}}

In every module where you want to use Data Binding, add the following plug-ins:

Apply plugin: 'com.android.application'

Apply plugin: 'com.android.databinding'

The Data Binding plug-in will add required and compiled configuration dependencies to your project.

3. Data Binding Layout file

Data Binding expression

The Data Binding layout file is a little different: the starting root tag is layout, followed by a data element and a root element of view. This view element is the root element of the layout file that you do not use Data Binding. Examples are as follows:

A variable property named user is described in data so that it can be used in this layout:

In layout's property expression writing @ {}, here is a TextView's text set to the firstName property of user:

Data object

Suppose you have a plain-old Java Object (POJO) for user:

Public class User {public final String firstName; public final String lastName; public User (String firstName, String lastName) {this.firstName = firstName; this.lastName = lastName;}}

This type of object has data that never changes. It is common in app and can be read once and never changed afterwards. Of course, you can also use JavaBeans objects:

Public class User {private final String firstName; private final String lastName; public User (String firstName, String lastName) {this.firstName = firstName; this.lastName = lastName;} public String getFirstName () {return this.firstName;} public String getLastName () {return this.lastName;}}

From Data Binding's point of view, the two classes are equivalent. The expression @ {user.firstName} for the android:text attribute in TextView accesses the firstName in the former POJO object and the getFirstName () method in the latter JavaBeans object.

Binding data

By default, a Binding class is generated based on the name of the layout file, converts it to Pascal case and adds the suffix "Binding". The above layout file is activity_main.xml, so the generated class name is ActivityMainBinding. This class contains all the bindings (such as the user variable) from the layout attribute to the Views of the layout, and it also knows how to assign a numeric value to the Binding expression. The easiest way to create a bindings is during inflating as follows:

@ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView (this, R.layout.main_activity); User user = new User ("Test", "User"); binding.setUser (user);} that's it. After running app, you will see Test User. Or you can get View by: MainActivityBinding binding = MainActivityBinding.inflate (getLayoutInflater ()); if you use DataBinding in ListView or RecyclerView adapter, you may use: ListItemBinding binding = ListItemBinding.inflate (layoutInflater, viewGroup, false); / / or ListItemBinding binding = DataBindingUtil.inflate (layoutInflater, R.layout.list_item, viewGroup, false)

4. Go deep into the Layout file

Import

Zero or more import elements may be used in data elements. These are only used to add references to your layout file, just like in Java:

Now, View can use your Binding expression:

When a class name conflicts, one of the class names can be renamed to alias::

In this way, Vista corresponds to com.example.real.estate.View and View corresponds to android.view.View in the layout file. Imported types can be used as references in Variable and expressions:

Note: Android Studio has not processed imports yet, so automatic import Variable cannot be used in your IDE. Your app will still compile properly, and you can use a fully compliant name in your Variable definition to solve the IDE problem.

Imported types can also use static properties and methods in expressions:

...

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

Variables

Any number of variable elements can be used in data. Each variable element describes an attribute for the Binding expression in the layout file.

This Variable type is checked at compile time, so if a Variable implements Observable or observable collection, this should be reflected in the type. If variable is a basic class or interface that does not implement the Observable interface, Variables will not be observed!

When there are different layout files for multiple configurations (for example, horizontal or vertical), the Variables is merged. There must be no conflicting Variable definitions between these layout files.

The resulting Binding class will have setter and getter for each described Variables. These Variables use the default Java values-null (reference type), 0 (int), false (boolean), and so on until setter is called.

Custom Binding class name

By default, the naming of the Binding class is based on the name of the layout file, starting with uppercase, excluding the underscore () and the * * letter capitalization after (), and then adding the "Binding" suffix. This class will be placed under the databinding package in a module package. For example, the layout file contact_item.xml will generate ContactItemBinding. If the module package is com.example.my.app, it will be placed in com.example.my.app.databinding.

The Binding class can be renamed or placed in a different package by adjusting the class attribute in the data element. For example:

...

A Binding class named ContactItem is generated in the databinding package of the module wrapper. If you want this class to be generated in different packages, you need to add a prefix, as follows:

...

In this case, the ContactItem class is generated directly in the module package. Or you can provide the entire package name:

...

Includes

Pass Variables from the container layout to an included layout by using application namespace and the Variable name in the attribute:

Note: user variable is required in name.xml and contact.xml layout files

Expression.

Common expressions are very similar to Java expressions, and the following are the same:

Mathematics +-/ *%

String concatenation +

Logic & & | |

Binary & | ^

Unary operation + -! ~

Shift > = Android:text= "@ {list [index]}"... Android:text= "@ {sparse [index]}"... Android:text= "@ {map [key]}"

String

When using single quotation marks to contain attribute values, it is easy to use double quotes in an expression:

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

It is also possible to use double quotes to include attribute values. You need to use "`" before and after the string:

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

It is also possible to use normal expressions to access resources:

Android:padding= "@ {large? @ dimen/largePadding: @ dimen/smallPadding}"

Formatting strings and plural numbers can be judged by providing parameters

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

When multiple parameters are required, all parameters will pass:

Have an orange Have d oranges android:text= "@ {@ plurals/orange (orangeCount, orangeCount)}"

Some resources require explicit type judgment:

Type normal reference expression reference

String [] @ array @ stringArray int [] @ array @ intArray TypedArray @ array @ typedArray Animator @ animator @ animator StateListAnimator @ animator @ color @ color ColorStateList @ color @ colorStateList

5. Data object

Any Plain old Java object (POJO) can be used with Data Binding, but modifying POJO does not cause UI updates. The real power of Data Binding is that it can notify your Data object when the data changes. There are three different data change notification mechanisms: Observable object, ObservableFields, and observable collections.

UI is also automatically updated when these observable Data objects are bound to UI,Data object properties.

Observable object

A class that implements the android.databinding.Observable interface can allow a listener to be attached to a Bound object to listen for changes in all properties on the object.

The Observable interface has a mechanism for adding and removing listeners, but it is up to the developer to manage notification or not. To make development easier, a base class for BaseObservable is created to implement the listener registration mechanism. The Data implementation class is still responsible for notifying when the property changes. This is done by specifying a Bindable comment to getter and notifications within setter.

Private static class User extends BaseObservable {private String firstName; private String lastName; @ Bindable public String getFirstName () {return this.firstName;} @ Bindable public String getFirstName () {return this.lastName;} public void setFirstName (String firstName) {this.firstName = firstName; notifyPropertyChanged (BR.firstName);} public void setLastName (String lastName) {this.lastName = lastName; notifyPropertyChanged (BR.lastName);}}

During compilation, the Bindable annotation generates an Entry in the BR class file. The BR class file is generated in the module package. If the base class for the Data class cannot be changed, the Observable interface is implemented through a convenient PropertyChangeRegistry for storing and effectively notifying listeners.

Observable field

Some small work involves creating Observable classes, so developers who want to save time or have few properties can use ObservableFields. ObservableFields is a self-contained observable object with a single field. It has all the basic types and one is a reference type. To use it, you need to create a public final field in the data object:

Private static class User extends BaseObservable {public final ObservableField firstName = new ObservableField (); public final ObservableField lastName = new ObservableField (); public final ObservableInt age = new ObservableInt ();}

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

User.firstName.set ("Google")

Int age = user.age.get ()

Observable collection

Some app use more dynamic structures to save data. The Observable collection allows keyed access to these data objects. ObservableArrayMap is a reference type for keys, such as String.

ObservableArrayMap user = new ObservableArrayMap (); user.put ("firstName", "Google"); user.put ("lastName", "Inc."); user.put ("age", 17)

In the layout file, you can access map through the string key:

... ObservableArrayList is an integer for keys: ObservableArrayList user = new ObservableArrayList (); user.add ("Google"); user.add ("Inc."); user.add (17)

In the layout file, you can access the list through the index:

... 6. Binding generation

The generation of the Binding class links variables and Views in layout. As discussed earlier, the name and package name of Binding can be customized. The generated Binding classes extend android.databinding.ViewDataBinding.

Create

Binding should be created immediately after inflation to ensure that the View hierarchy does not disturb binding-to-views expressions in layout before. There are several methods that can be bound to a layout. The most common is to use static methods on the Binding class. The inherate method loads the View hierarchy and binds to it only with this step. There is a simpler version that only requires LayoutInflater and one that uses ViewGroup:

MyLayoutBinding binding = MyLayoutBinding.inflate (layoutInflater)

MyLayoutBinding binding = MyLayoutBinding.inflate (LayoutInflater, viewGroup, false)

If you use a different mechanism to load layout, it can bind it separately:

MyLayoutBinding binding = MyLayoutBinding.bind (viewRoot)

Sometimes Binding cannot know in advance, in which case, you can use the DataBindingUtil class to create a Binding:

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

Views with ID

In layout, a public final field is generated for each View with ID. Binding does a single pass on the View hierarchy to extract Views with ID. This mechanism is faster than some Views using findViewById. For example:

It generates the following Binding class:

Public final TextView firstName

Public final TextView lastName

IDs is not as unnecessary as it is without Data Bindings, but there are still some instances that need to access Views from the code.

Variables

Each Variable has an access method.

It generates setters and getters in Binding:

Public abstract com.example.User getUser (); public abstract void setUser (com.example.User user); public abstract Drawable getImage (); public abstract void setImage (Drawable image); public abstract String getNote (); public abstract void setNote (String note)

ViewStubs

ViewStubs is slightly different from normal Views. They are initially invisible, and when they are either set to be visible or explicitly told to load, they replace themselves by loading another layout.

Since ViewStub basically disappears from the View hierarchy, the View on Binding objects must also disappear to allow collection. Because Views is *, a ViewStubProxy object fetches ViewStub, which gives the developer ViewStub when it exists and can also access the loaded View hierarchy when ViewStub has been loaded.

When loading another layout, you must create a Binding for the new layout. Therefore, ViewStubProxy must listen to ViewStub's OnInflateListener listener and establish Binding at that time. Because only one can exist, ViewStubProxy allows developers to set an OnInflateListener on it that will be called after the Binding is established.

Binding advance

Dynamic Variables

Sometimes, you don't know the specific Binding class, for example, a RecyclerView adapter doesn't know the specific Binding class for arbitrary layouts operations. It still has to be assigned to Binding during onBindViewHolder.

In this example, all layouts bound by the RecyclerView have a Variable of "item". The BindingHolder has a getBinding method that returns ViewDataBinding.

Public void onBindViewHolder (BindingHolder holder, int position) {final T item = mItems.get (position); holder.getBinding (). SetVariable (BR.item, item); holder.getBinding (). ExecutePendingBindings ();}

Direct Binding

When a variable or observable changes, the binding is planned to change before the next frame. There are many times, but it must be done immediately in the case of Binding. To enforce it, use the executePendingBindings () method.

Background thread

As long as it is not a collection, you can change your data model in background threads. Data Binding localizes each Varialbe/field when determining whether to avoid any concurrency problems.

7. Property Setters

Whenever the bound value changes, the generated Binding class must call the setter method. The Data Binding framework has custom methods for assigning values.

Automatic Setters

For a property, Data Binding tries to find the setAttribute method. It has nothing to do with the namespace of the attribute, just the name of the attribute itself.

For example, an expression about the android:text attribute of TextView looks for a method of setText (String). If the expression returns a setText (int) method that int,Data Binding will search for. Note: for the expression to return the correct type, use casting if necessary. Data Binding still works even if no property with the given name exists. You can then easily "create" attributes for any setter through Data Binding. For example, DrawerLayout does not have any attributes, but a large number of setters. You can use one of these using automatic setters.

Renamed Setters

Some properties with setters do not match by name. For these methods, properties can be associated with BindingMethods annotations. This must be associated with a class that contains BindingMethod annotations, each for a renamed method. For example, the android:tint attribute is associated with setImageTintList, not setTint.

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

In the above example, it is unlikely that developers need to rename setters, and the android schema properties have been implemented.

Custom Setters

Some properties require custom binding logic. For example, there is no associated setter for the android:paddingLeft attribute. On the contrary, setPadding (left, top, right, bottom) exists in. A static binding adapter method with BindingAdapter annotations allows developers to customize how setter invokes a property.

The properties of Android have created BindingAdapters. For example, for paddingLeft:

BindingAdapter ("android:paddingLeft") public static void setPaddingLeft (View view, int padding) {view.setPadding (padding, view.getPaddingTop (), view.getPaddingRight (), view.getPaddingBottom ());}

Binding adapters are very useful for other custom types. For example, a custom loader can be used to load images asynchronously.

When there is a conflict, the Binding adapter created by the developer overrides the Data Binding default adapter.

You can also create an adapter that can receive multiple parameters.

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

The adapter will be called if both ImageViewimageUrl and error are used and imageUrl is a string type and error is a drawable.

Custom namespaces will be ignored during the matching process.

You can also write adapters for Android namespaces.

8. Conversion

Object conversion

When an object is returned from an Binding expression, a setter is selected from the automatic, renamed, and custom setters. The object will be converted to the parameter type of the selected setter.

This is for the convenience of those who use ObservableMaps to save data. For example:

An object is returned in userMap and is automatically converted to the parameter type of setText (CharSequence). Developers need to convert in expressions when there may be confusion about parameter types.

Custom conversion

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

Here, the background requires a Drawable object, but the color is an integer. Whenever there is a Drawable and the return value is an integer, the integer type is converted to ColorDrawable. This conversion is done by using a static method with BindingConversion annotations:

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

Note: conversion occurs only at the setter level, so it does not allow the following mixing types:

Read here, this "how to use the Data Binding library to declare layouts files" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report