开始你的kotlin?

来源:互联网 发布:对称加密算法 java 编辑:程序博客网 时间:2024/09/21 08:54

网上看到太多的kotlin语法介绍,基础语法,个人觉得学习东西实践是进度最快的,但是看到网上关于如何开始kotlin的文章比较少,或者是这种太简单,所以没啥人写,所以我来作个记录
首先看下官网的介绍
kotlin官网https://kotlinlang.org/docs/tutorials/kotlin-android.html

···
Installing the Kotlin plugin
The Kotlin plugin is bundled with Android Studio starting from version 3.0. If you use an earlier version, you’ll need to install the Kotlin plugin. Go to File | Settings | Plugins | Install JetBrains plugin… and then search for and install Kotlin. If you are looking at the “Welcome to Android Studio” screen, choose Configure | Plugins | Install JetBrains plugin… You’ll need to restart the IDE after this completes
···
这是官网的介绍,意思就是3.0的android studio自带支持库,在创建项目的时候,可以勾选,include kotlin support支持
这里写图片描述
不过我相信很多人不会选择升级3.0,因为现在大多数的项目都是java的,这里选择第二个方法,下载kotlin插件,首先新建一个android studio的hello world项目
file-setting-plugins 在里面搜索kotlin插件下载,也可以自己导入在官网下载的插件
下面是kotlin插件下载的官网
https://plugins.jetbrains.com/plugin/6954-kotlin
不过这些都比较慢,作为雷锋的我,把这个下载好后上传到了这里
这个是android studio2.4版本的
http://download.csdn.net/detail/qq_15527709/9862355
这个是android studio2.2版本的
http://download.csdn.net/detail/qq_15527709/9864645
好像每个android studio对应的kotlin版本插件都是不同的,需要别的版本的大家可以自行去文中的链接去下载

这里写图片描述
好 安装好插件之后

重启android studio
继续看下官网的说法

Converting Java code to KotlinOpen MainActivity.java file. Then invoke action Convert Java File to Kotlin File. You can do it by several ways. The easiest one is to invoke Find Action and start typing an action name (like in a screencast below). Alternatively you can call this option via the Code | Convert Java File to Kotlin File menu entry or by using the corresponding shortcut (you can find it at the menu entry).

打开mainactivity使用快捷键ctrl+shift+a出现一个框框输入convert java file to kotlin file
这里写图片描述
或者你可以点击code菜单最下方的选项也是可以的
这里写图片描述

covert java file to kotlin file 点击之后你的mainactivity就会变成这样了

package com.example.sunwentao.kotlinimport android.support.v7.app.AppCompatActivityimport android.os.Bundleclass MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)    }}

然后这个时候你运行你的helloworld项目,然后闪退了,会提示你kotlin没有设置
继续官网寻求解决办法
这里写图片描述
这里写图片描述

简单的流程解释,点击configure会弹出一个框框,//todo注意这里选择你在官网下载的版本(官网说的是选择最新的,但是如果你下载的不是最新的,adnroid studio又会给你下一遍的),点击ok,这个时候android studio提示你可以同步了sync now点击同步,在你的build.gradle中会自动帮你添加好支持

最后 在运行,然后你的kotlin hello world出来,然后 开始学习吧。。。
实践 进度才最快- - 或者你可以copy你写好的java文件到这个项目在转换为kotlin观察变化

原创粉丝点击