最近的I/O大會上kotlin被google定為官方語言,并在AS3.0上也已經(jīng)搭載,筆者也搭上學(xué)習(xí)的車。
1.基本配置
打開Android studio株婴, 在Plugins中的Browse Repositories中輸入"kotlin",點(diǎn)擊 Install, 沒有翻墻下載會很慢并且會出現(xiàn)錯誤暑认,多下幾次就行了,下載完成后 在一個(gè)Activity界面 選擇 工具欄的 code ——> Convert java file to kotlin file, 這時(shí)候你的Activity 代碼就會變成
class TestActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
}
}
這個(gè)之后再分析
現(xiàn)在 運(yùn)行是會出錯的大审, 要點(diǎn)擊右上角的“Configure”進(jìn)行配置
//配置過后 project的build.gradle
buildscript {
ext.kotlin_version = '1.1.2-4'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
//配置過后 module的build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'//增加特性(剔除了findViewById())
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.example.leon.kotlintest"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
現(xiàn)在基本配置完成蘸际,也可以運(yùn)行了
2.控件操作
在module的build.gradle中增加
apply plugin: 'kotlin-android-extensions'//增加特性(剔除了findViewById())
然后在布局文件 這是兩個(gè)TextView, id分別為 text1徒扶、text2
之后再activity中直接通過 id.text設(shè)置(比databinding還方便)
text1.text = "Hello Kotlin!"
text2.textSize = 18.0f
再在布局中寫個(gè)Button粮彤,id為btn1
btn1.setOnClickListener {toast("Hello leon")} //點(diǎn)擊彈出toast
toast需要 新建一個(gè) .kt文件, 寫一個(gè)方法
fun Context.toast(msg:String){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
這樣只要一行代碼 就實(shí)現(xiàn)了點(diǎn)擊btn彈出toast
由此我們可以看出姜骡,kotlin中 函數(shù)的寫法: 由關(guān)鍵字‘fun’聲明
而 msg:String 表示String類型导坟,與java寫法相反并加了一個(gè)“:”
變量聲明: var、 val
var 是可變的
val 不可變圈澈,常量
剛開始寫kotlin代碼惫周,有很多錯誤,可以java文件里編寫康栈,在復(fù)制過來轉(zhuǎn)換递递,慢慢的就記住了,這個(gè)要用到項(xiàng)目中還不太現(xiàn)實(shí)啥么,還是有很多的坑登舞,但終究是大勢所趨,還是要好好學(xué)習(xí)的悬荣。