Android studio 2 手把手教你使用kotlin插件

Kotlin for Android

最近谷歌IO大会, 把kotlin纳入了Android开发首选语言, 估计这与谷歌和oracle一直在打官司的缘故分不开吧, 而且kotlin本身就很好用,不只是增加语法糖,而且kotlin-native是基于自己的runtime, 跨平台的.好了, 废话不多说,自己体会kotlin的好. 之前讲了 [android studio3.0预览版使用kotlin], 但是很多涌进来的新人在android studio2.0中使用kotlin有问题, 我现在就来演示一次, 希望有所帮助!(假定已经拥有了开发Android的基础, 约定Android Studio简称as)

安装kotlin插件(安装后重启as生效)

安装后重启生效

新建工程

这里写图片描述
然后Next. 添加empty Activity, 然后等待gradle去下载依赖, build

快捷添加kotlin支持

这里写图片描述
选择版本:
这里写图片描述
自动添加了kotlin所需要的依赖
这里写图片描述

把activity转换成kotlin的

这里写图片描述
转换后的activity就是kotlin写的了, 非常简单, 在xml里面添加textview的id

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.i7play.kotlintest.MainActivity">

    <TextView
        android:id="@+id/tv_text"
        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" />

</android.support.constraint.ConstraintLayout>

然后在代码里面写:

class MainActivity : AppCompatActivity() {

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

        val tvText = findViewById(R.id.tv_text) as TextView
        tvText.text = "测试一下"
    }
}

不写findViewById

kotlin的黑科技,可以不写繁琐的findViewById, 只需要在app/build.gradle里面添加一个apply就可以了

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

现在可以直接写在xml里面定义的控件id

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*//多引入的包

class MainActivity : AppCompatActivity() {

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

        //val tvText = findViewById(R.id.tv_text) as TextView
        //tvText.text = "测试一下"
        tv_text.text = "测试一下" //不要写findViewById(R.id.tv_text) as TextView,是不是很爽?
    }
}

怎么学kotlin?

-我觉得最好去看下官网的文档:https://kotlinlang.org/
-github里面搜搜kotlin, 一大堆开源app,可以多学学.
-不要动不动就去问别人, 自己先搜答案,网上多得是答案, kotlin 2012年就开源了!
-先跟着文档学!!! 也有中文文档:https://github.com/huanglizhuo/kotlin-in-chinese
-最后, 新手请教的时候一定要谦虚, 并没有人有义务回答问题, 零android基础, 零java基础的人好好看文档吧.
-QQ群:516157585

猜你喜欢

转载自blog.csdn.net/qq634416025/article/details/72625218