Android Studio 配置Kotlin详解

插件安装

安装这个kotlin插件
Paste_Image.png

  1. project的build.gradle配置
  1. buildscript新增

    1
    2. dependencies新增```classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

  2. allprojects新增

    1
    2
    3
    4
    > 2. module的build.gradle配置
    1. 新增插件支持

apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’

1
2. android新增

sourceSets {
main.java.srcDirs += ‘src/main/kotlin’
}

1
3. dependencies新增

compile “org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version”

1
2
#### 总配置

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
ext.kotlin_version = ‘1.1.2-4’
repositories {
jcenter()
}
dependencies {
classpath ‘com.android.tools.build:gradle:2.3.1’
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()
mavenCentral()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
```
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.happy.kotlindemo"
minSdkVersion 15
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'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
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 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

所有都配置好了之后,选择一个Activity文件,选择code->convet java file…

Paste_Image.png

大功告成

Paste_Image.png