美文网首页
Kotlin Android 绑定视图xml

Kotlin Android 绑定视图xml

作者: 这个杀手不太累 | 来源:发表于2017-10-31 09:21 被阅读517次

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

  • 首先Create Android Project


    这里写图片描述

    创建好的工程build.gradle文件中会自动应用Kotlin插件,我们不需要再添加其它依赖


    这里写图片描述
  • xml文件中定义控件id

```

<?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在定义好的控件了,是不是很简单
    这里写图片描述

相关文章

网友评论

      本文标题:Kotlin Android 绑定视图xml

      本文链接:https://www.haomeiwen.com/subject/bjbvpxtx.html