data binding library笔记

https://developer.android.com/topic/libraries/data-binding/expressions#kotlin 在build.gradle文件中配置

android{
	...
	dataBingding{
		enabled true
	}
	...
}

设置原先xml的跟元素为layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="user" type="com.example.User"/>
   </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="@{user.lastName}"/>
   </LinearLayout>
</layout>

Expressions within the layout are written in the attribute properties using the "@{}" syntax

声明xml中使用的变量,使用这样的语法.

Note that < needs to be escaped as < 注意,为了xml的语法正确,所有在表达式总使用到的<都需要转义成&lt

<data>
	<variable name="user" type="com.example.User" />
	//也支持使用import倒入其他的类
    <import type="android.util.SparseArray"/>
    <import type="java.util.Map"/>
    <import type="java.util.List"/>
    <variable name="list" type="List&lt;String>"/>
    <variable name="sparse" type="SparseArray&lt;String>"/>
    <variable name="map" type="Map&lt;String, String>"/>
    <variable name="index" type="int"/>
    <variable name="key" type="String"/>
</data>

Binding data A binding class is generated for each layout file. By default, the name of the class is based on the name of the layout file, converting it to Pascal case and adding the Binding suffix to it.

activity_main.xml --> ActivityMainBinding

The recommended method to create the bindings is to do it while inflating the layout, as shown in the following example.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val binding: ActivityMainBinding = DataBindingUtil.setContentView(
            this, R.layout.activity_main)

    binding.user = User("Test", "User")
}

If you are using data binding items inside a Fragment, ListView, or RecyclerView adapter, you may prefer to use the inflate() methods of the bindings classes or the DataBindingUtil class, as shown in the following code example:

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

表达式语言中不支持这些操作 this super new

Null coalescing operator The null coalescing operator (??) chooses the left operand if it isn't null or the right if the former is null.

android:text="@{user.displayName ?? user.lastName}"
// functionally equivalent to
android:text="@{user.displayName != null ? user.displayName : user.lastName}"
```	

**Avoiding null pointer exceptions**
Generated data binding code automatically checks for null values and avoid null pointer exceptions. 
For example, in the expression @{user.name}, if user is null, 
user.name is assigned its default value of null. 
If you reference user.age, where age is of type int, 
then data binding uses the default value of 0.

**Event handling**
You can use the following mechanisms to handle an event:

1. Method references: 
   In your expressions,you can reference methods that conform to the signature of the listener method. 
   When an expression evaluates to a method reference, 
   Data binding wraps the method reference and owner object in a listener, 
   and sets that listener on the target view. 
   If the expression evaluates to null, Data binding doesn't create a listener and sets a null listener instead.

2. Listener bindings: 
   These are lambda expressions that are evaluated when the event happens. 
   Data binding always creates a listener, which it sets on the view. 
   When the event is dispatched, the listener evaluates the lambda expression.

**One major advantage compared to the View onClick attribute is that the expression is processed at compile time, 
so if the method doesn't exist or its signature is incorrect, you receive a compile time error.**

class MyHandlers { fun onClickFriend(view: View) { ... } }

The binding expression can assign the click listener for a view to the onClickFriend() method, as follows:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="handlers" type="com.example.MyHandlers"/> <variable name="user" type="com.example.User"/> </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}" android:onClick="@{handlers::onClickFriend}"/> </LinearLayout> </layout>


**Note: The signature of the method in the expression must exactly match the signature of the method in the listener object.**

**Type aliases**
When there are class name conflicts, one of the classes may be renamed to an alias. 
The following example renames the View class in the com.example.real.estate package to Vista:

<import type="android.view.View"/> <import type="com.example.real.estate.View" alias="Vista"/> ```

Just as in managed code, java.lang.* is imported automatically. import语法甚至可以用在静态方法,比如这样

<data>
    <import type="com.example.MyStringUtils"/>
    <variable name="user" type="com.example.User"/>
</data>

<TextView
   android:text="@{MyStringUtils.capitalize(user.lastName)}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>

**Data binding doesn't support include as a direct child of a merge element. ** Data bingding不支持merge标签

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:bind="http://schemas.android.com/apk/res-auto">
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <merge><!-- Doesn't work -->
       <include layout="@layout/name"
           bind:user="@{user}"/>
       <include layout="@layout/contact"
           bind:user="@{user}"/>
   </merge>
</layout>

转载于:https://my.oschina.net/tanghaoo/blog/3047119

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值