Kotlin for Android

在Google IO 2017 大会上,Google将 Kotlin列为 Android官方开发语言,Android Studio 3.0 也默认集成了Kotlin插件。

Android Studio 3.0目前是预览版,下载地址:
https://developer.android.google.cn/studio/preview/index.html

如果您是更早的版本,点击Android Studio File->Settings->Plugins,搜索Kotlin,然后重启Android Studio。

Kotlin相对Java语言更加简洁,虽然与Java语法并不兼容,但Kotlin被设计成可以和Java代码相互运作,并可以重复使用Java编写好的框架。也就是说一个项目允许Java和Kotlin共同开发的,不会有任何兼容性的问题。

接下来我们就来演示下使用Kotlin创建Android工程

创建工程

创建工程

使用Android Studio 3.0版本,创建工程时勾选 Include Kotlin support 选项,这是和之前唯一一处不同。

此处默认生成MainActivity.kt 相当于之前的MainActivity.java

//冒号表示继承 相当于Java中的extends
class MainActivity : AppCompatActivity() {
    //问号表示该变量可以为空
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

项目目录下的build.gradle文件 也有些变化:


buildscript {
    ext.kotlin_version = '1.1.2-4' //指定了Kotlin的版本号
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
        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()
        maven { url 'https://maven.google.com' }
        mavenCentral()
    }
}

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

app/build.gradle文件也添加了kotlin-android插件

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.a520wcf.kotlin"
        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'
        }
    }
}

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 "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
}

如果你使用是Android Studio 3.0以下的版本,gradle文件中需要你自己手动配置。

创建新的类时也可以选择使用kotlin或者Java语言

Kotlin和Java语法对比

Kotlin总体而言要简洁一些。
1.设置点击事件
先回忆Java写法

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    ...
  }
});

再来对比Kotlin写法

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
  ...
}

2.条目点击事件
先看Java写法

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
    = new BottomNavigationView.OnNavigationItemSelectedListener() {
  @Override
  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case R.id.navigation_home:
        mTextMessage.setText(R.string.title_home);
        return true;
      case R.id.navigation_dashboard:
        mTextMessage.setText(R.string.title_dashboard);
        return true;
    }
    return false;
  }
};

再来看下Kotlin写法

private val mOnNavigationItemSelectedListener
    = BottomNavigationView.OnNavigationItemSelectedListener { item ->
  when (item.itemId) {
    R.id.navigation_home -> {
      mTextMessage.setText(R.string.title_home)
      return@OnNavigationItemSelectedListener true
    }
    R.id.navigation_dashboard -> {
      mTextMessage.setText(R.string.title_dashboard)
      return@OnNavigationItemSelectedListener true
    }
 }
 false
}

更多精彩请关注微信公众账号likeDev
这里写图片描述

猜你喜欢

转载自blog.csdn.net/yulianlin/article/details/72628764
今日推荐