Google 正式宣布 Android Studio 3.0 將會正式支援 Kotlin
這也讓 Kotlin 成為目前熱烈討論的程式語言之一
和 Java 一樣,Kotlin 也是一個 JVM 的語言,由 JetBrains 所開發
因此,Kotlin 和 Java 是可以同時並存一起使用的
至於 Kotlin 會不會取代 Java,以及 Kotlin 和 Java 誰比較好的問題
在這邊就不多作討論,因為這是滿主觀的問題
所以在這邊主要會介紹,怎麼運用 Kotlin 在 Android APP 的開發上
- 安裝 Kotlin plugin
到 Preference 下的 plugin 頁面來安裝 Kotlin plugin
- Hello Kotlin App
先看原本 Java 的寫法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
TextView textView = (TextView) findViewById(R.id.textView); | |
textView.setText("Java Style"); | |
} | |
} |
接下來看怎麼用 Kotlin 改寫
首先,先設置好 Kotlin,按下 cmd + shift + a,搜尋 kotlin,選擇 configure kotlin in project
Kotlin 寫法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val textView = findViewById(R.id.textView) as TextView | |
textView.text = "Kotlin Style" | |
} | |
} |
<ps> 在一開始不知道怎麼寫 kotlin 的時候,也可以用 cmd + shift + a -> Convert Java File to Kotlin File 來看怎麼寫
整體來看,好像沒有差別很大,也沒有變得比較簡潔
比較有差別的地方是,可以不用使用 setText(),而變成直接用 property 的方式來設定 text
其實 Kotlin 還有更簡潔的寫法(資料來源)
在 module 的 build.grandle 裡面,加入下面這段 code
apply plugin: 'kotlin-android-extensions'
這時候可以進一步改寫成
不用再使用 findViewById 來找到 TextView,可以直接使用 ID 來存取該 TextView
- 下一步
沒有留言:
張貼留言