DataBinding系列三、表达式

来源:互联网 发布:iphone软件开发教程 编辑:程序博客网 时间:2024/05/16 10:38

使用数据绑定的布局文件中,对属性赋值的是表达式,这样可以在绑定时执行特定代码,减少工作量。表达式是有特殊语法的。

Imports

导入功能,和java中的import功能一样,导入之后就能使用类的静态属性和方法了,也可以用来定义对像。

其中 java.lang.* 是默认被导入了。

语法是:

<data>
   <importtype="xxx.xxx.xx"alias="other_name"/>
</data>

例如:

 <data>
      <!-- 导入View类,后面使用 -->
      <importtype="android.view.View" />
      <variable
          name="user"
          type="com.heyy.databindingexample.User" />
  </data>
  <ImageView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@mipmap/ic_launcher"
          android:visibility="@{View.VISIBLE}" />

Variables

变量或者对像,定义后可以访问它的方法或属性,之前已经使用过了。但是有一些要注意的地方:

1.默认定义了一个context变量,它的值是view.getContext(),如果自己再定义一个叫context变量就会覆盖它。

2.为不同配置(例如landscape / portrait)定义的多个布局文件里面的varianble会自动合并。

3.databing会为每个varianble生成一对getter/setter,当没有设置数据时,variable提供的属性是默认值。

4.data binding会自动检查表达式中variable为空的情况,比如user为空时,user.displayName会返回null。

操作符

目前支持以下操作

Mathematical + - / * %

String concatenation +

Logical && ||

Binary & | ^

Unary + - ! ~

Shift >> >>> <<

Comparison == > < >= <=

instanceof

Grouping ()

Literals - character, String, numeric, null

Cast

Method calls

Field access

Array access []

Ternary operator ?:

举个栗子:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@mipmap/ic_launcher"
    android:visibility="@{user.age>=18?View.VISIBLE:View.GONE}" />

不支持以下操作

this

super

new

Explicit generic invocation

空操作符??

android:text="@{user.displayName ?? user.lastName}"

当user.displayName不为空时返回 user.displayName,否则返回user.lastName

集合操作符[]

像arrays, lists, sparse lists, maps等集合类,需要使用[]操作符来访问里面的元素,例如

<layoutxmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <importtype="java.util.List" />
       <variablename="list"type="List" />
   </data>
   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@{list[0]}" />
</layout>

字符串

表达式中的字符串的引号要特殊处理,几种可用的格式是:

android:text='@{map["firstName"]}'
android:text="@{map[`firstName`}"
android:text="@{map['firstName']}"
android:text="@{map[&quot;firstName&quot;]}"



0 0