原文鏈接地址
Google I/O 大會后瘫析,Android Studio 就發(fā)布了3.0 金絲雀版本江醇,支持 Kotlin 語言,增加了 Gradle 編譯速度幌墓,支持即時應用開發(fā)但壮,在 Android O 模擬器中增加了 Google Play Store,自適應圖標等 20 多項新功能常侣。今天我們不討論Android Studio 3.0 使用Kotlin,我會在后面的博客中介紹蜡饵,今天是討論和學習android studio 2.0+ 版本如何使用Kotlin。廢話不多說胳施,我們直上使用步驟(說明:假定已經擁有了開發(fā)Android的基礎, 約定Android Studio簡稱AS)
一溯祸、AS安裝kotlin插件(安裝后重啟AS生效)
不同的系統(tǒng)打開不太一樣:我用的的蘋果的mac系統(tǒng)
Mac:Android Studio --> Preferences --> Plugins --> Browse repositories --> 輸入kotlin --> 找到Kotlin點擊 --> 點擊 install
Windows:File --> Settings --> Preferences --> Plugins --> Browse repositories --> 輸入kotlin --> 找到Kotlin點擊 --> 點擊 install
等待.....下載完成之后,重啟android studio
二舞肆、 新建一個工程
然后Next. 添加empty Activity 焦辅,Next-->Finish 等待項目build完成
三、添加kotlin支持
選擇Android with Gradle
選擇版本
等待asyn 椿胯,自動添加了kotlin所需要的依賴
四筷登、把Activity轉化為kotlin
1,選擇MainActiviy ---> Code 工具欄 ---> Convert Java File to Kotlin File
轉化后的activity就是用kotlin寫的了
2哩盲,現在我們需要在xml文件中給控件TextView添加一個id:tv_text
<em><?</em>xml version="1.0" encoding="utf-8"<em>?></em><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.niwoxuexi.kotlindemo.MainActivity"> <TextView android:id="@+id/tv_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>
3前方,MainActivity中添加代碼測試:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //新添加的代碼 val textTv = findViewById(R.id.tv_text) as TextView textTv.text = "Hello Kotlin!" }}
4,在kotlin中可以不用謝findViewById ,只需要在app/build.gradle中添加:apply plugin: 'kotlin-android-extensions'就可以了
apply plugin: 'com.android.application'apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'
5廉油,現在只需要更改MainActiviy.kotlin的代碼為
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //新添加的代碼 // val textTv = findViewById(R.id.tv_text) as TextView // textTv.text = "Hello Kotlin!" //不用findViewById惠险,是不是很簡單呀 tv_text.text="Hello Kotlin!" }}
ok,現在我們就完成了在Android Studio 2+ 上開發(fā)kotlin的Android app了抒线,
最后上代碼現在地址:www.niwoxuexi.com