databinding学习(2)

在布局中import引入类java

<data>
    <import type="android.view.View"
        alias="MyView"/>

能够直接使用 View或者避免冲突时使用别名alias

在布局中可使用表达式android

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="test"
    android:visibility="@{user.isAdult ? MyView.VISIBLE : MyView.GONE}"/>

能够在布局中让对象调用public方法app

ndroid:text="@{user.printTest()}"
public String printTest() {
    return "测试打印";
}

能够在布局中导入类型,而且调用静态方法布局

public class Test {
    public static String print(String content) {
        return  "this is Test.print() : "+content;
    }
}
<import type="com.example.lin.myapplication.model.Test"/>
<TextView
    android:layout_width="wrap_content"
    android:text="@{Test.print(user.firstName)}"
    android:layout_height="wrap_content" />

在布局中能够像java代码中导入类型,在变量声明时候再也不写全类的包名测试

<import type="com.example.lin.myapplication.model.User"/>
<variable
    name="user"
    type="User"/>

布局中声明变量this

<variable
    name="testStr"
    type="String"/>

binding类就会有 这个testStr变量的 get set方法code


Null Coalescing 运算符对象

android:text="@{user.displayName ?? user.lastName}" 就等价于 android:text="@{user.displayName != null ? user.displayName : user.lastName}"

使用资源数据事件

<dimen name="large_sp">20sp</dimen>
<dimen name="small_sp">10sp</dimen>
<variable
    name="large"
    type="boolean"/>
android:textSize="@{large? @dimen/large_sp : @dimen/small_sp}"

在onClick事件中写上ci

binding.setLarge(!binding.getLarge());

能够进行大小的切换

相关文章
相关标签/搜索