Kotlin Android 綁定視圖xml

在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在定義好的控件了,是不是很簡單
    這里寫圖片描述
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容