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中的变量也就相当于一个自定义的属性,将值传递至自定义属性而已。也可以使用自定义的实体,只需类型相同即可,在这里不详细介绍,小伙伴可以自己试试。

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