Kotlin Android扩展_视图绑定

来源:互联网 发布:专科 知乎 编辑:程序博客网 时间:2024/06/05 21:49

KotLin视图绑定

从Kotlin M11开始增加的扩展插件使得Android开发者更容易取得XML文件中定义的Views。你可能会觉得它很像ButterKnife,但使用起来更简单。

Kotlin Android扩展本质上是一个视图绑定,使得开发者在代码中通过id就可以使用XML文件中定义的Views。它将自动为Views创建属性值,而不用使用第三方注解框架或者findViewById函数。

要使用这个特性,首先需要安装插件“Kotlin Android Extension”,并在build.gradle文件的构建脚本依赖中增加一个新的classpath:

org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version

如果想在Activity中使用这个文件里面定义的Views,你只需要导入这个xml文件的synthetic属性值,如下所示:

import kotlinx.android.synthetic.<xml_name>.*

具体到我们的例子,则如下所示:

import kotlinx.android.synthetic.main.activity_main.*;

那么在真实的activity中的用法:

        message.text = "Hello Kotlin!"

message为什么,如下布局文件activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"               xmlns:tools="http://schemas.android.com/tools"                android:layout_width="match_parent"                android:layout_height="match_parent"                android:paddingLeft="@dimen/activity_horizontal_margin"                android:paddingRight="@dimen/activity_horizontal_margin"                android:paddingTop="@dimen/activity_vertical_margin"                android:paddingBottom="@dimen/activity_vertical_margin"                tools:context=".MainActivity">    <TextView        android:id="@+id/message"        android:text="@string/hello_world"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></RelativeLayout>

也就是说,通过id直接绑定了view,是不是比Android中第三方框架来得更爽!
例子源码

原创粉丝点击