AndroidStudio使用kotlin入门

作者: b77535296c81 | 来源:发表于2017-05-27 09:43 被阅读9626次

AndroidStudio使用kotlin入门

导读
<a name="label">1、创建第一个kotlin项目</a>
<a name="label">2、java代码自动转换成kotlin代码</a>
<a name="label">3、开始Hello world</a>
(ps:由于Markdown在简书里对锚点的支持效果不是很好,就没设置跳转)

什么是Kotlin?

Kotlin 是由 JetBrains 开发,一个基于 JVM 的新的编程语言。
Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JVM的设备上运行。
谷歌 I/O 2017宣布将支持 Kotlin 作为Android开发的第一语言
目前AndroiStudio 3.0预览版本已自带Kotlin插件,无需做任何的配置即可开始体验。但如果是之前的版本,则需要我们自行做些配置。
通过 File | Settings | Plugins | Install JetBrains plugin… 搜索并安装 Kotlin 插件。
插件安装完成后(需要重启下AndroidStudio),就开始创建我们的第一个Kotlin项目了

1、创建第一个kotlin项目

这个过程跟我们以往创建新的项目没有任何区别,选择 Start a new Android Studio project 或者 File | New project。 根据弹出的对话框提示进行操作,直接下一步直到finish吧</a>

Android Studio 3.0 在当前对话框中提供启用 Kotlin 支持的选项,勾选后可以跳过 “配置 Kotlin 工程(Configuring Kotlin in the project)”的步骤。


命名工程: 选择Android SDK版本: 选择需要创建的 Activity 样式: 命名Activity:

<br />

2、java代码自动转换成kotlin代码

有两种方式可以实现java代码自动转换成kotlin代码:
  • 第一种方法,使用FIND ACTION(快捷键:ctrl+shift+a)<br />
    打开选中activity文件,快捷键呼出FIND ACTION,输入 Convert Java File to Kotlin File 指令,按确定<br />



    <br />



    <br /><br />
    搞定,我们现在看到的MainActivity就是kotlin代码了<br />
    package com.example.kotlindemo
    import android.support.v7.app.AppCompatActivity
    import android.os.Bundle
    
    class MainActivity : AppCompatActivity() {
    
      override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      }
    }
    

<br />

  • 第二种方法,通过菜单栏依次调出 Code | Convert Java File to Kotlin File 或使用快捷键(菜单栏入口可见)完成操作
    <br />
    code——>Convert Java File to Kotlin File选型——>确定<br />



    <br />



    <br />

    <br />
    <br />

    此时我们仅仅是把java代码转成的Kotlin代码,但是还不能去编辑,因为此时kotlin还没配置好,我们可以试着在MainActivity里面去修改代码,发现AS会弹出提示框,配置kotlin到项目里面也非常的简单,只需要按照提示操作进行即可完成<br />



    <br />看到这个提示框,直接点确定<br />
    <br /><br />
    会发现自动打开了build.gradle文件,并且在头部多出了一行kotlin的配置代码,build.gradle文件有变动,我们重新编译下项目,这时因为需要下载kotlin的相关文件,所以可能需要些时间<br />
    build.gradle文件<br />
    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android'
    android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
      applicationId "com.example.kotlindemo"
      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 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    

    }
    repositories {
    mavenCentral()
    }
    最外层的build.gradle也相应的多处了kotlin的配置代码<br />

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
    
    buildscript {
    ext.kotlin_version = '1.1.2-4'//kotlin的版本号
    repositories {
        jcenter()
    }
    dependencies {
      classpath 'com.android.tools.build:gradle:2.3.0'
      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"//kotlin插件
    
      // 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
    }
    

3、开始Hello world<br />

在开始写代码之前,我们再进行一个比较实用的配置,可以让我们不用再写findViewById代码。配置也很简单,两行代码搞定
首先在moudle的build.gradle文件头部加上这行代码:<pre> <code>apply plugin: 'kotlin-android-extensions'</code></pre>此时我们需要重新编译下项目,然后打开MainActivity,在导包配置中,添加如下代码:

<pre> <code>import kotlinx.android.synthetic.main.<layout>.*</code></pre><layout>需要根据自己项目的xml文件名进行替换,如我的xml文件名是<code> activity_main </code>就应该这样添加导包:
<pre> <code> import kotlinx.android.synthetic.main.activity_main.*</code></pre>
activity_main.xml代码很简单,和以往没什么区别:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.kotlindemo.MainActivity">

  <Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

   <Button
    android:id="@+id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello Kotlin!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

   <Button
    android:id="@+id/btn3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello Android!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

MainActivity.kt代码也是很简单,仅仅实现了一个Button点击弹出Toast的效果

package com.example.kotlindemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(),View.OnClickListener(){

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

    btn1.setOnClickListener(this)
    btn2.setOnClickListener(this)
    btn3.setOnClickListener(this)

}

override fun onClick(v:View){
  when(v?.id){
      R.id.btn1 -> showToast("${btn1.text}")
      R.id.btn2 -> showToast("${btn2.text}")
      R.id.btn3 -> showToast("${btn3.text}")
  }
}


fun showToast(str:String){
    Toast.makeText(this,str,Toast.LENGTH_LONG).show();
}

}

相关文章

网友评论

  • _孑孓_:请问下, android studio上能否像 java module一样,可以直接执行 kotlin的main 方法, 如何配置
  • 48f82f6cf0b1:引入kotlinx的时候报错,请指教
  • MigrationUK:我测试的 View.OnClickListener() 的() 要去掉呢
  • 家电维修技师:谢谢分享

本文标题:AndroidStudio使用kotlin入门

本文链接:https://www.haomeiwen.com/subject/zosffxtx.html