Android studio 2.2 2.3 2.4 如何使用kotlin插件

原文鏈接地址 (附帶小視頻講解)

Google I/O 大會後,Android Studio 就發佈了3.0 金絲雀版本,支持 Kotlin 語言,增加了 Gradle 編譯速度,支持即時應用開發,在 Android O 模擬器中增加了 Google Play Store,自適應圖標等 20 多項新功能。今天我們不討論Android Studio 3.0 使用Kotlin,我會在後面的博客中介紹,今天是討論和學習android studio 2.0+ 版本如何使用Kotlin。廢話不多說,我們直上使用步驟(說明:假定已經擁有了開發Android的基礎, 約定Android Studio簡稱AS)

一、AS安裝kotlin插件(安裝後重啓AS生效)

不同的系統打開不太一樣:我用的的蘋果的mac系統

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+ 上開發kotlin的Android app了,

最後上代碼現在地址:www.niwoxuexi.com


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章