Kotlin Android扩展_视图绑定

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中第三方框架来得更爽!
例子源码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值