Android Studio 配置Kotlin

来源:互联网 发布:directx游戏编程入门 编辑:程序博客网 时间:2024/05/21 17:31

最近在群里看到很多人都在聊Kotlin这门新语言,而且也成为了android开发语言之一,熟话说人无远虑必有近忧呀,如果会Kotlin的开发者越来越多,公司在招聘的时候就该提出这个要求了。
想去使用Kotlin开发android项目,就要集成对Kotlin语言支持的配置,Android Studio 3.0之后就不需要配置了已经自动集成好了。我用的是3.0之前的所以还要配置一下。

添加Kotlin插件

选择Settings>Plugins去搜索Kotlin
这里写图片描述
这里添加了Kotlin语言库和序列化对象Parcelable

创建Kotlin类文件或者activity

在我们下载好插件之后,在去new文件时会多出两个选项
这里写图片描述
这个时候我们去新建一个Kotlin File/Class,android studio就会提示我们去配置Kotlin
这里写图片描述
点击配置,就会弹出一个对话框
这里写图片描述
点击Ok
会自动的在项目的gradle和Module 的gradle中添加依赖
项目的gradle:

// 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.2'        //Kotlin相关        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 的gradle:

apply plugin: 'com.android.application'  //kotlin相关apply plugin: 'kotlin-android'android {    compileSdkVersion 25    buildToolsVersion "25.0.2"    defaultConfig {        applicationId "com.kotlintest"        minSdkVersion 19        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 'com.android.support:appcompat-v7:25.3.0'    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'    testCompile 'junit:junit:4.12'    //kotlin相关    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"}repositories {    mavenCentral()}

将java代码转为Kotlin语言编写的

这里写图片描述
转之前的Java代码:

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}

转之后的Kotlin代码

class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)    }}

以后的学习中,这种java代码和Kotlin之间的转换可以有助你的理解。
上传了一个Kotlin学习的pdf中文版点击下载

原创粉丝点击