Kotlin的配置和使用

在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.Bundle
import android.support.v7.app.AppCompatActivity
import org.jetbrains.anko.toast


class KotlinActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        toast("Hello Kotlin");
    }
}

学习ing,加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值