Android databinding(四)--layout中的特殊使用

        在上面幾篇文章中我們介紹了databinding在layout,activity,自定義屬性(bind adapter)的使用。本篇文章重要簡介的是databinding在layout中的一些特殊使用。

一、include的使用


        在Android開發中使用include是經常的,使用include可以減少單個的layout文件的代碼量,也可以使用layout的複用,將一些經常使用的layout封裝供其他頁面的調用,在我們的data binding中也是可以的,但是有一個問題在databinding中使用include如何使用數據的傳遞呢?下面我們來看看:

1、first_layout

<layout xmlns:bind="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="data"
            type="String"/>
    </data>
 <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
     <include layout="@layout/tow_layout"
                app:data="@{data}"/>
</android.support.design.widget.CoordinatorLayout>
</layout>

2、tow_layout

<layout xmlns:bind="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="data"
            type="String"/>
    </data>
 <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
      <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:maxLines="1"
             android:ellipsize="end"
             android:text="@{data}"/>
</LinearLayout>
</layout>

        從以上兩個佈局文件中,我們可以看見data binding中include的使用也是一樣的使用的,傳遞數據的話,只要在引用的文件定義同樣的數據傳遞進去即可。例如:app:data=”@{data}”,第一個data是tow_layout定義的變量,第二個是first_layout中的變量,傳遞至tow_layout中。在這裏我們看出來include中的變量也就相當於一個自定義的屬性,將值傳遞至自定義屬性而已。也可以使用自定義的實體,只需類型相同即可,在這裏不詳細介紹,小夥伴可以自己試試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章