Android Studio配置Kotlin開發環境的最簡單方式

來源:互聯網
上載者:User

標籤:tor   extension   roi   osi   uri   ges   tin   技術   class   

開啟Settings面板,找到Plugins選項,點擊Browse repositories(瀏覽倉庫),輸入“Kotlin”尋找,然後安裝即可。安裝完成之後需要重啟Android Studio (切記!)。

安裝完成之後如所示。

外掛程式當前的最新版本是1.1.2-release-Studio-2.3-3

第二步:配置Kotlin開發環境

點擊功能表列的“Tools”選項,選擇“Kotlin”,然後選擇“Configure Kotlin in Project”。如所示。

在彈出的視窗中選擇需要使用Kotlin的模組Kotlin編譯器和運行時的版本,如所示。

點擊“OK”之後,Kotlin外掛程式會自動開始配置。配置完成之後,同步一下工程(Sync Project)即可。

[可選]:在功能表列中點擊“Code”功能表項目,選擇“Convert Java File to Kotlin File”即可根據之前配置將已有的Java檔案轉換為Kotlin檔案。

附:推薦配置

開啟模組下的build.gradle檔案,在apply plugin: ‘kotlin-android‘下面加入一行:apply plugin: ‘kotlin-android-extensions‘。這是一個Kotlin的擴充模組,可以讓Activity自動關聯xml布局中的View而不需要findViewById
詳情請參考:http://kotlinlang.org/docs/tutorials/android-plugin.html

附:使用Kotlin編寫單元測試

在Android開發中免不了要進行各種單元測試,使用Kotlin編寫單元測試可以簡化代碼,提高效率。
將工程切換到Project視圖,展開模組下的src目錄,這個目錄下預設會有三個檔案夾。main檔案夾通常用來存放模組代碼;androidTest檔案夾通常用來存放Android相關的單元測試;test檔案夾通常用來存放Java(Kotlin)相關的單元測試。

Kotlin的單元測試

在測試包下建立一個Kotlin Class,例如命名為UnitTest1。在這個類中可以編寫多個測試方法,不詳細敘述。

package cc.duduhuo.kotlintestimport org.junit.Testimport org.junit.Assert.*class UnitTest1 {    @Test    fun addition_isCorrect() {        assertEquals(4, (2 + 2).toLong())    }}
Android的單元測試

在測試包下建立一個Kotlin Class,例如命名為AndroidTest1。在這個類中可以編寫多個測試方法,不詳細敘述。

package cc.duduhuo.kotlintestimport android.support.test.InstrumentationRegistryimport android.support.test.runner.AndroidJUnit4import org.junit.Assert.assertEqualsimport org.junit.Testimport org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class AndroidTest1 {    @Test    fun useAppContext() {        // Context of the app under test.        val appContext = InstrumentationRegistry.getTargetContext()        assertEquals("cc.duduhuo.kotlintest", appContext.packageName)    }}
附:有關Kotlin的一些有用資料
  1. Kotlin官網:http://kotlinlang.org/
  2. Kotlin使用者手冊(英文):http://kotlinlang.org/docs/reference/
  3. Kotin開源地址:https://github.com/JetBrains/kotlin
  4. 官方介紹如何開始使用Kotlin:http://kotlinlang.org/docs/tutorials/getting-started.html
  5. 與Kotlin相關一些庫、架構和應用:http://kotlinlang.org/docs/resources.html

Android Studio配置Kotlin開發環境的最簡單方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.