Kotlin Android Studio环境搭建

2019-03-19  本文已影响0人  翻译不了的声响

在Google I/O 2017中,Google 宣布 Kotlin 成为 Android 官方开发语言。那么我们就来看看如何在 Android Studio上创建一个简单的 Kotlin 项目。

1. 下载安装
2. 创建项目

1)点击 File —— New —— New Project... 创建项目;

创建项目

2)选择创建项目类型,选择Phone and Tablet —— Empty Activity,点击 Next 下一步;

项目类型

3)配置项目相关信息,点击 Finish 完成;

配置项目

4)项目创建完成。

创建完成
3. Kotlin配置

如果AS版本是 3.0+,在创建项目时勾选 Include Kotlin support 就会自动配置Kotlin;如果 AS版本低于 3.0,就需要手动配置 Kotlin。

Kotlin手动配置步骤:
1)在项目根目录下build.gradle文件中添加依赖的 Kotlin插件版;

buildscript {
    ext.kotlin_version = '1.3.21' //新增
    repositories {
        google()
        jcenter()        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.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
    }
}
...

2)在项目 app目录下build.gradle文件中配置引用 Kotlin库,并点击 Sync Now 重新编译项目;

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'//新增
apply plugin: 'kotlin-android-extensions'//新增

...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"//新增
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

3)在菜单栏选择 Code —— Convert Java File to Kotlin File,将 Java 代码转换为 Kotlin;

代码转换

4)配置转换完成。

转换完成
上一篇 下一篇

猜你喜欢

热点阅读