Kotlin Android 绑定视图xml

在Android Studio3.0中默认支持使用Kotlin来编写Android程式。
在用Kotlin写的Activity绑定视图文件中不须要使用findViewById,让咱们看下如何使用Kotlin绑定视图。android

  • 首先Create Android Project
    这里写图片描述
    建立好的工程build.gradle文件中会自动应用Kotlin插件,咱们不须要再添加其它依赖
    这里写图片描述web

  • xml文件中定义控件idsvg

<?xml version="1.0" encoding="utf-8"?>
<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">

    <TextView android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World" android:textAllCaps="false" />

	</RelativeLayout>
  • 在Activity直接使用定义好的控件
    这里写图片描述
    这里要注意下,直接使用message会报红,按Alt+Enter键选择import,导入**import kotlinx.android.synthetic.main.activity_main.***就能够直接使用咱们在xml在定义好的控件了,是否是很简单
    这里写图片描述