1. 程式人生 > >【每天積累一點點】Data Binding Library官方教程翻譯

【每天積累一點點】Data Binding Library官方教程翻譯

Data Binding Library

This document explains how to use the Data Binding Library to writedeclarative layouts and minimize the glue code necessary to bind yourapplication logic and layouts.

The Data Binding Libraryoffers both flexibility and broad compatibility — it's a support library, soyou 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 forGradle.

這篇文章用於說明如何用Data Binding Library去寫佈局檔案並且用盡可能少的膠水程式碼將組織你的應用邏輯和佈局檔案組織起來。

Data Binding Library即靈活有具有很好的相容性-它是一個支援庫,可以使用它的最低版本是Android2.1。

Gradle的最低版本要求是1.5.0-alpha1,如需更新請看update the Android Plugin for Gradle.

Build Environment

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

首先從SDK管理器的Support repository中下載這個庫。

To configure your app touse data binding, add the dataBinding

 element to your build.gradle file in the app module.

要使用這個庫,你需要在你的app module中的build.gradle中新增dataBinding元素。

Use the following code snippet to configure data binding:

看考下面的程式碼片段圖配置data binding:

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

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

如果你的應用中的子模組也要用到data binding,這個子模組也要配置build.gradle。

Also, make sure you areusing a compatible version of Android Studio. Android Studio 1.3 and later provides support for databinding as described in Android Studio Support forData Binding.

並且,也要確保你的Studio版本也要相容databinding。Android Studio 1.3以及更高版本都相容。

Data Binding Layout Files


Writing your first set of data binding expressions

開始你的第一次data binding表示式

Data-binding layout files are slightly different and startwith a root tag of layout followed by a data elementand a view root element. This view element iswhat your root would be in a non-binding layout file. A sample file looks likethis:

Data-binding佈局檔案與普通的佈局檔案有些許的不同,Data-binding佈局檔案以layout作為根標籤,裡面包含了data標籤和view根元素。這個view根元素就和你以前沒有使用Data-binding時的寫法一樣。下面是一個小栗子。

<?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">
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"/>
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.lastName}"/>
   </LinearLayout>
</layout>

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

Data標籤裡的user變數是一個佈局中可能會用到的屬性值。

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

Expressions within thelayout are written in the attribute properties using the "@{}" syntax. Here, theTextView's text is set to the firstName property of user:

佈局檔案中控制元件裡的表示式寫法是"@{}",例如這裡的TextView的text的值就是user物件中的firstName的屬性值。

<TextView android: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:

假如現在有一個簡單的java物件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 hasdata that never changes. It is common in applications to have data that is readonce and never changes thereafter. It is also possible to use a JavaBeansobjects:

這種型別的物件永遠不會改變。通常在應用程式中之被賦值一次之後不會再發生變化。

或者用一個JavaBean物件。

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 the perspective ofdata binding, these two classes are equivalent. The expression @{user.firstName} used for the TextView's android:textattribute will accessthe firstName field in the former class and the getFirstName() method in the latter class. Alternatively, it will also beresolved tofirstName() if that method exists.

在data binding看來,上面這兩個類完全相同。表示式@{user.firstName} 將會訪問前一個類的firstName 屬性和後一個類的getFirstName()方法。二者選一都可以,事實上,當User的屬性(例如firstName)是私有時,@{user.firstName}表示式識別的是方法名,

可以識別getFirstName()firstName(),其它方法無法識別,也不是識別的return值。

Binding Data

By default, a Binding class will be generated based on thename of the layout file, converting it to Pascal case and suffixing"Binding" to it. The above layout file was main_activity.xml so the generate class was MainActivityBinding. This class holds all thebindings from the layout properties (e.g. theuser variable) to the layout's Views and knows how to assignvalues for the binding expressions.The easiest means for creating the bindingsis to do it while inflating:

預設情況下,Binding類會根據佈局檔案的名字以帕斯卡命名法(駝峰)再加上字尾Binding來自動生成。例如,上面的佈局檔案的名字是 main_activity.xml 所以自動生成了 MainActivityBinding這個類掌控者佈局檔案中所有控制元件繫結著的資料,並且通過表示式來分配值。最簡單的建立binding的方式是當填充佈局的時候:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
   User user = new User("Test", "User");
   binding.setUser(user);
}

You're done! Run theapplication and you'll see Test User in the UI. Alternatively, you can get theview via:

上面簡單的幾行程式碼就binding成功了,然後執行應用你就會看到“Test”和“User”。

也可以通過下面的方式建立bind。

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

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

如果在ListView或RecyclerView的adapter中,你也可以通過如下方式建立bind。

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

Event Handling

更新中。。。。。。