您的位置:首页 > 其它

DataBinding-xml中使用include

2017-08-31 14:47 411 查看

DataBinding-xml中使用include

需要include的xml文件

该文件同其他普通的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>


使用include

上面代码简单在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>


重点有两处:

bind: bind:showEmptyView=“”,这里需要使用bind来绑定我们include布局中的showEmptyView变量,然后还需要定义bind的命名空间 xmlns:bind=”http://schemas.android.com/apk/res-auto”

include标签需要给一个id:否则的话想用include的布局中的控件ID是无法使用的,给定include标签一个id如include,那么在binding中就可以使用binding.include.recyclerView就可以来操作RecyclerView了。

谢谢观看

该项目Sunshine已放在GitHub,这是其中一篇开发记录,更多开发记录文章请点击该项目查看。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息