Data Binding
生成的綁定類用來訪問佈局中的變量和 view
控件。本章講述了怎麼建立和自定義生成的綁定類。android
綁定類保存了變量和 view
變量的綁定關係。綁定類的包路徑和名字都是能夠自定義的。全部生成的綁定類都繼承了 ViewDataBinding
類。ide
每一個佈局文件都會生成一個對應的綁定類,默認狀況下,綁定類的名字取決於佈局文件的名字,佈局文件的名字轉爲駝峯寫法並添加 Binding
後綴。如 activity_main.xml
佈局文件對應的綁定類是 ActivityMainBinding
。佈局
綁定對象應該在加載佈局的時候當即實例化,可使用 inflate
方法,以下所示:this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: MyLayoutBinding = MyLayoutBinding.inflate(layoutInflater)
}
複製代碼
inflate
還有一個重載方法,以下所示:spa
val binding: MyLayoutBinding = MyLayoutBinding.inflate(getLayoutInflater(), viewGroup, false)
複製代碼
若是佈局已經使用其餘的方式加載了,可使用以下方式綁定:code
val binding: MyLayoutBinding = MyLayoutBinding.bind(viewRoot)
複製代碼
有時候,綁定類的類型是不知道的,可使用 DataBindingUtil
的 bind
方法:xml
val viewRoot = LayoutInflater.from(this).inflate(layoutId, parent, attachToParent)
val binding: ViewDataBinding? = DataBindingUtil.bind(viewRoot)
複製代碼
對於佈局文件中每一個有 id
的控件,都會在綁定類中生成一個對應的字段。以下所示,針對佈局文件中的 TextView
,綁定類分別生成了 firstName
和 lastName
兩個字段與之對應:對象
<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}"
android:id="@+id/firstName"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName}"
android:id="@+id/lastName"/>
</LinearLayout>
</layout>
複製代碼
綁定類一次性保存了每個有 id
的控件實例,這比 findViewById()
高效得多。繼承
對於佈局文件中聲明的每個變量,DataBinding
都在綁定類中生成了對應的 get()
和 set()
方法。以下所示,變量 user
、 image
、 note
,在綁定類都有對應的訪問方法:get
<data>
<import type="android.graphics.drawable.Drawable"/>
<variable name="user" type="com.example.User"/>
<variable name="image" type="Drawable"/>
<variable name="note" type="String"/>
</data>
複製代碼
不一樣於一般的 view
,ViewStub
是一個不可見的 view
,當它調用 inflate
等方法顯示的時候,它會被其餘佈局替代。
ViewStub
在調用 inflate
等方法後會被其餘 view
替代,因此須要考慮綁定類中的 ViewStub
實例的回收和新生成 view
的綁定問題。因此在綁定類中並無生成 ViewStub
實例,而是生成了 ViewStubProxy
實例,當 ViewStub
存在的時候,ViewStubProxy
能夠用來訪問它;當 ViewStub
被其餘 view
替代後,ViewStubProxy
能夠用來訪問這個新的 view
。
ViewStubProxy
必須監聽 ViewStub
的 OnInflateListener
,當收到通知的時候,創建與新佈局的綁定關係。咱們能夠給 ViewStubProxy
設置一個 OnInflateListener
,當與新佈局創建綁定關係後,會通知這個監聽器。
當數據變化時,view
會在下一幀開始更新,若是咱們須要 view
當即更新,能夠調用 executePendingBindings()
方法。
假若有一個 content_item.xml
的佈局文件,默認的綁定類名是 ContentItemBinding
,默認的路徑是包名。
以下所示,咱們能夠自定義綁定類名爲 ContentItem
,路徑爲 com.example
:
<data class="com.example.ContactItem">
…
</data>
複製代碼