Android Data binding information binding detailed _android

Source: Internet
Author: User
Tags unsupported android data binding

Last year, the Google I/O conference introduced a very powerful new framework databinding, the data binding framework has brought us great convenience, before we may need to write a lot of findviewbyid in each activity, not only trouble, but also increased the coupling of code, If we use databinding, we can discard so many Findviewbyid, save time and effort. Here, in fact, there are many fast online annotation frame, but the annotation frame and databinding want to use, and the official website document said databinding also can improve parsing XML speed, in fact, databinding good, Not only can be omitted to use a lot of long-winded Findviewbyid, there are many. Look down and you'll understand.

Before introducing databinding, we must first learn to build the environment to use it. Given that it was released last year, now everyone as the version is estimated at more than 1.5, on the 1.5 version of the build and introduction bar, 1.5 before everyone can search on the Internet, because I see most of the Internet is the introduction of the use of 1.3, there are not many for the 1.5 after the environment to build a method.

Environment construction

Android's Gradle plugin version is not less than 1.5.0-ALPHA1:
Classpath ' com.android.tools.build:gradle:1.5.0 '
Then modify the Build.grade of the corresponding module (module):

Android {
 ....
 . dataBinding {
  enabled = True
 }
}

Note: The Android Stuido version must be greater than 1.3, and Android studio currently does not have an automatic code hint for the binding object and will only check at compile time.

It is so simple, but 1.3 and previous versions of the environment, the building, may be a bit of a hassle (no 1.3 of the environment to build methods, the Internet is much).

Basic Show

Before we give a specific explanation, let's use a simple example to learn the basics and show off the databinding's great charm, and you'll be attracted by its simple features.

Let's start with a Java bean, which is a very simple user class.

Package Loonggg.net.databinding.bean;

/**
 * Created by loongggdroid on 2016/3/14.
 *
/public class User {
 private String name;
 Private String age;

 Public User (string name, String age) {
  this.name = name;
  This.age = age;
 }

 public void SetName (String name) {
  this.name = name;
 }

 public void Setage (String age) {
  this.age = age;
 }

 Public String GetName () {return
  this.name;
 }

 Public String Getage () {return
  this.age
 }}


Second, look at what it looks like when you use the DataBinding layout file. The main changes are in the layout layout file.

<?xml version= "1.0" encoding= "Utf-8"?> <layout xmlns:android=
"http://schemas.android.com/apk/res/" Android ">

 <data>
  <variable
   name=" user "
   type=" Loonggg.net.databinding.bean.User " >
 </data>

 <linearlayout
  android:layout_width= "match_parent"
  android:layout_height= "Match_parent"
  android:orientation= "vertical" >

  <textview
   android:layout_width= "WRAP_" Content "
   android:layout_height=" wrap_content "
   android:text=" @{user.name} "/>

  <textview
   android:layout_width= "wrap_content"
   android:layout_height= "wrap_content"
   android:text= "@{" User.age} "/>
 </LinearLayout>
</layout>

See here, some people may start a bit confused, did not give the control to define the ID, but with the @{} method, in the end what is going on? First of all, I'll explain to you later, and we'll see how we can get the values in, and how to use them in the activity.

Package loonggg.net.databinding;

Import android.app.Activity;
Import Android.databinding.DataBindingUtil;
Import Android.os.Bundle;

Import Loonggg.net.databinding.bean.User;
Import loonggg.net.databinding.databinding.ActivityMainBinding;

public class Mainactivity extends activity {
 @Override
 protected void onCreate (Bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  activitymainbinding binding = Databindingutil.setcontentview (this, r.layout.activity_main);
  User user = New User ("Loonggg", "n");
  Binding.setuser (user);
 }



See activity is not feeling very concise, very refreshing, without the control initialization Findviewbyid, and then go to SetText (), just add two lines of code.
Run the results, needless to say, obviously, will definitely show Loonggg and 23, the effect chart is as follows:

Basic explanation

Layout life

Example we have introduced, for example, some of the new things, it is necessary to explain, Java bean There is no explanation, we must all understand, we will start from the layout file. Rather than using XML, the root node is transformed into layout by a specific layout (such as LinearLayout), which includes both the data node and the traditional view. The data node here is like a bridge linking View and Modle. By declaring a variable variable in this data node, the value can be easily uploaded to the layout file.

<?xml version= "1.0" encoding= "Utf-8"?> <layout xmlns:android=
"http://schemas.android.com/apk/res/" Android ">

<!--type" is the declaration of our user entity class users, must be written in full, with the package name, we give this entity class named User-->
 <data>
  < Variable
   name= "user"
   type= "Loonggg.net.databinding.bean.User"/>
 </data> 
 < Linearlayout> ...
 </LinearLayout>
</layout>

Variable name is User

Variable type is "Loonggg.net.databinding.bean.User"

Type is declared that our user entity class user, must write full, with the package name, we give this entity class named User,textview in the @{user.name} is to display the name of this user, age is the same.

Binding variable

Although the corresponding in the layout file, but how the value is passed in? That's the two lines of code in the activity that we're going to be doing, and it binds the entity classes to the layout files. Modify the OnCreate in mainactivity, replace Setcontentview () with Databindingutil.setcontentview (), and then create a user object, through Binding.setuser ( User) is bound with variable.

@Override
 protected void onCreate (Bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  activitymainbinding binding = Databindingutil.setcontentview (this, r.layout.activity_main);
  User user = New User ("Loonggg", "n");
  Binding.setuser (user);
 }

Advanced usage

Import usage

In fact, the data node also supports import usage, such as:

<data>
  <import type= "Loonggg.net.databinding.bean.User"/>
  <variablename= "User" type= " User "/>
</data>

Note here : Import does not import xx.xxx.* like Java, it must be specific to the name of each class to be imported.

Same class name

Here you may ask if you import two classes with the same name? Don't be afraid, people think very thoughtful, can play the individual name or nickname it! For example:

···
<data> 
 <import type= "xxx. User "alias=" myuser > 
 <import type= "Xxx.xx.User" > 

 <variable name= 
   "user" 
   type= "user" > 
 <variable 
   name= "myuser" 
   type= "MyUser"/> 
</data> 
<textview xxx:@{ Myuser.getname ()}> 
<textview xxx:@{user.getname ()}>
...

Advanced usage of variable definitions
On top, we learned how to define some simple variables in XML. We don't define set variables such as list, map, and so on. So how do you define this set variable? In fact, the definition of the way we are basically consistent, the difference is that we also need to define key for it variables, such as:

<layout xmlns:android= "Http://schemas.android.com/apk/res/android" > <data> <import type= "android.gr" Aphics. Bitmap "/> <import type=" java.util.ArrayList "/> <import" type= java.util.HashMap "/> <!--Collection 
    The definition--> <variable name= "list" type= "arraylist<string>"/> <variable "Map" Type= "hashmap<string, string>"/> <variable name= "array" type= "string[]"/> <!--as collection Define the corresponding index--> <variable name= "Listkey" type= "int"/> <variable name= "Mapkey" type= "St 
    Ring "/> <variable name=" Arraykey "type=" int "/> <!--string, boolean and int use--> <variable 
    Name= "str" type= "String"/> <variable name= "Error" type= "Boolean"/> Name= "num" type= "int"/> </data> <linearlayout android:orientation= "vertical" android:lay Out_width= "Match_Parent "android:layout_height=" wrap_content "> <textview android:layout_width=" wrap_content "Andro id:layout_height= "Wrap_content" android:text= "@{list[listkey]}/> <textview android:layout_width=" Wra P_content "android:layout_height=" wrap_content "android:text=" @{map[' name '} "/> <textview Android : layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@{array[0]}"/> <TextV 
   Iew android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@{str}"/> <textview android:layout_width= "wrap_content" android:layout_height= wrap_content "android:text=" @{Stri

 Ng.valueof (num)} "/> </LinearLayout> </layout>

Binding of events

You can import android.view.View.OnClickListener directly in XML and develop its click events.

<variable
 name= "Clicklistener"
 type= "Android.view.View.OnClickListener"/>
...
 android:onclick= "@{clicklistener}" ...

Holder.binding.setClickListener (New View.onclicklistener () {
   @Override public
   void OnClick (View v) {
    // Do something
  });

An expression

In fact, the XML file still supports expressions, such as the following:

<textview
 android:layout_width= "wrap_content"
 android:layout_height= "Wrap_content"
 android: Text= ' @{error? "Error": "OK"} '/>

This is the use of a Boolean value.

Now let's take a look at the syntax and unsupported syntax of the expression support

Supported Expressions:

    1. Mathematical +-/*%
    2. String concatenation +
    3. Logical && | |
    4. Binary & | ^
    5. Unary +-! ~
    6. Shift >> >>> <<
    7. Comparison = = > < >= <=
    8. instanceof
    9. Grouping ()
    10. Literals-character, String, numeric, NULL
    11. Cast
    12. Method calls
    13. Field Access
    14. Array Access []
    15. Ternary operator?:

Unsupported expression:

    1. This
    2. Super
    3. New
    4. Explicit Generic Invocation

Assignment method for controls with IDs

The assignment of controls in an XML file can actually be implemented in Java files, as well. I'll take the top simple example, if you give a TextView the ID set is as follows:

<textview
   android:id= "@+id/name"
   android:layout_width= "Wrap_content"
   Wrap_content "
   />

This assignment in the activity:

@Override
 protected void onCreate (Bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  activitymainbinding binding = Databindingutil.setcontentview (this, r.layout.activity_main);
  Binding.name.setText ("Non-famous programmer");
 }

See here the basis of most of the finished, in fact there are many more advanced usage, such as in the ListView how to use and so on, we can go to their own access to information learning, so that the understanding can be more profound. I hope this article will be helpful to everyone. DataBinding you can start using it now.

The above is to the Android data binding information collation, follow-up to continue to supplement the relevant information thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.