该文件同其他普通的xml文件相同,用layout标签包裹其他内容,需要的变量定义在data中,代码如下:
<?xml version="1.0" encoding="utf-8"?> <layout> <data> <import type="android.view.View" /> <variable name="showEmptyView" type="boolean" /> </data> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="@{showEmptyView ? View.VISIBLE : View.GONE}"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@mipmap/ic_placeholder" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="12dp" /> </FrameLayout> </layout>上面代码简单在data中定义了一个boolean型的变量showEmptyView。接下来我们在其他布局中引入该布局的时候就需要用到这个变量,并赋值给他,如下代码所示:
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="viewModel" type="xxx.xxx.xxx.ViewModel" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/color_bg" android:orientation="vertical"> <include android:id="@+id/include" layout="@layout/include_recycler" android:layout_width="match_parent" android:layout_height="match_parent" bind:showEmptyView="@{viewModel.showEmptyView}" /> </LinearLayout> </layout>该项目Sunshine已放在GitHub,这是其中一篇开发记录,更多开发记录文章请点击该项目查看。