Kotlin的配置和使用

来源:互联网 发布:罗慕路斯 知乎 编辑:程序博客网 时间:2024/06/05 22:41

在Google I/O 2017中,Google 宣布 Kotlin 成为 Android 官方开发语言。

本文是在android studio(2.3.1)中使用的方法,别的开发开发工具要自己找答案。(可以查看http://www.runoob.com/kotlin/kotlin-eclipse-setup.html )给菜鸟教程打广告啦!
步骤:
1.在android studio中点击setting—plugins—输入kotlin—-install—-重启android studio 。
2.配置:在project中找build.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'    ext.anko_version = '0.10.0-beta-2'    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()    }}task clean(type: Delete) {    delete rootProject.buildDir}

在app中的build.gradle添加代码

apply plugin: 'com.android.application'//需要加入代码apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'android {    compileSdkVersion 26    buildToolsVersion "26.0.0"    defaultConfig {        applicationId "com.example.miio.demoaggregate"        minSdkVersion 15        targetSdkVersion 26        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:26.+'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    testCompile 'junit:junit:4.12'    //需要加入代码    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"    compile "org.jetbrains.anko:anko-common:$anko_version"}

是不是很简单啊!
3.Android切换到kotlin语言:点击code—– Convert Java File to Kotlin File就可以了。
4.Kotlin转换到Android:如果不想使用kotlin在代码中点击右键—-local history只能回到没有编写kotlin以前不能保存写过的代码。
5.来一个简单toast

import android.os.Bundleimport android.support.v7.app.AppCompatActivityimport org.jetbrains.anko.toastclass KotlinActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        toast("Hello Kotlin");    }}

学习ing,加油!