Jet_DataBinding

2019/01/04

Jetpack DataBinding

1. 前期工作

1.1 建立环境

android {
    ...
    dataBinding {
        enabled = true
    }
}

1.3 AS支持DataBinding

1.4 DataBinding编译器

  1. gradle.properties中添加android.databinding.enableV2=true
  2. 通过gradle命令启用编译器 gradle -Pandroid.databinding.enableV2=true

2. 布局和绑定表达式

2.1 layout —— activity_main.layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="user" type="com.xxx.User"/>
				<import type="android.util.SparseArray"/>
				<variable name="sparse" type="SparseArray<String>"/>
		
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"/>
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{sparse[index]}"/>
   </LinearLayout>
</layout>

2.2 数据对象

data class User(val firstName: String, val lastName: String)

2.3 绑定数据

  1. 编译后生成ActivityMainBinding
  2. MainActivity中绑定

     val binding: ActivityMainBinding = DataBindingUtil.setContentView(
             this, R.layout.activity_main)
     binding.user = User("Test", "User")
    
  3. Fragment/View/Adapter等绑定

     val listItemBinding = ListItemBinding.inflate(layoutInflater, viewGroup, false)
    或者
     val listItemBinding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false)
    

    2.4 表达式

    Mathematical + - / * %  <——>  android:text="@{String.valueOf(index + 1)}"
    String concatenation +  <——> android:transitionName='@{"image_" + id}'
    Logical && ||
    Binary & | ^  
    Unary + - ! ~ 
    Shift >> >>> << 
    Comparison == > < >= <=	 
    instanceof 
    Grouping ()
    Literals - character, String, numeric, null	——> android:text="@{user.displayName ?? user.lastName}"
    Cast
    Method calls
    Field access	
    Array access [] 
    Ternary operator ?:	——> android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}"
    res <——> android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"
    

2.5 方法调用

  1. User类中定义点击事件处理方法 fun onClickUser(view: View) { ... }

  2. 调用 android:onClick="@{User::onClickUser}"

  3. CallBack类中定义事件回调 fun onSaveClick(view: View, user: User){}

  4. 调用

    ``` <?xml version=”1.0” encoding=”utf-8”?>

文内导航