原文地址: https://medium.com/google-developers/android-data-binding-that-include-thing-1c8791dd6038#.jxnxq3463
在上篇文章中, 講述了在Android Studio1.5及之后的版本上, 使用data binding來替代findViewById是多么簡單的一件事. 我展示了如何使用Android Studio來基于layout文件生成一個(gè)類似ViewHolder的類.但是如果layout中使用了 "include" 或 "merge"標(biāo)簽怎么辦?
Data Binding默認(rèn)也支持這些標(biāo)簽, 但是每個(gè)layout文件都會(huì)被生成一個(gè)不同的類. 例如
hello_world.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<include
android:id="@+id/included"
layout="@layout/included_layout"/>
</LinearLayout>
</layout>
included_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/world"/>
</layout>
需要用下面的方式來訪問不同的TextView:
HelloWorldBinding binding =
HelloWorldBinding.inflate(getLayoutInflater());
binding.hello.setText(“Hello”);
binding.included.world.setText(“World”);
include標(biāo)簽的命名規(guī)則跟View的命名規(guī)則是一樣的: "include"標(biāo)簽的id被
當(dāng)作成員變量名. 被include的layout文件會(huì)生成一個(gè)自己的類, 里面的view
也會(huì)被賦值給成員變量. 開發(fā)者也可以很容易的分別共享的id, 例如如果你
include了一個(gè)layout兩次:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<include
android:id="@+id/world1"
layout="@layout/included_layout"/>
<include
android:id="@+id/world2"
layout="@layout/included_layout"/>
</LinearLayout>
</layout>
同名的"world" TextView可以很容易被訪問:
HelloWorldBinding binding =
HelloWorldBinding.inflate(getLayoutInflater());
binding.hello.setText(“Hello”);
binding.world1.world.setText(“First World”);
binding.world2.world.setText(“Second World”);
記住要給include標(biāo)簽一個(gè)id, 否則不會(huì)為其生成公共成員變量. 同時(shí),記住在外面
使用 <layout> 標(biāo)簽. 這回觸發(fā)預(yù)處理過程, 生成類并綁定view.
如果你去查看生成的類, 會(huì)發(fā)現(xiàn)無論被include多少次, 他們使用的都是同一個(gè)類.
例如你有另外一個(gè)layout文件goodbye_world.xml也包含了included_layout.xml文件,那么只會(huì)生成一個(gè)類.