使用Kotlin重构项目

  |     |   本文总阅读量:

前言

上周大概花了一个星期的时间初步学习了一下Kotlin,并且同步写了Kotlin 笔记,方便后面使用的时候查询一些语法的用法。

一周的Kotlin学习下来,虽然只掌握了Kotlin的皮毛,但仍被其简单便捷的语法吸引。目前Kotlin已经成为Android的官方推荐语言,所以建议有时间的同学不妨学习一下,相信一定可以帮助你提高开发效率的。

这里就不介绍Kotlin的语法使用,既然初步学习了Kotlin,那么就在实践中检验一下,使用的是之前的毕业设计项目

,这个项目总体来说很适合初学者,所以就拿它上手,改起来相对比较简单。

所以本篇文章就介绍一下KotlinAndroid中的使用,相信你会爱上他的。

先看一下运行效果吧,跟之前快毕业了,撸个小项目效果是一模一样,所以大致看一下即可:

运行效果.gif

这里就展示一下基本的效果,想要了解详情的就fork一下我的代码吧:QNews

使用步骤

1. Android Studio集成Kotlin插件

通过Android Studio添加Kotlin插件:

Kotlin插件

进行相关的配置:

相关配置

集成好了,记得同步一下,这个时候在build.gradle下会生成对Kotlin插件的引用:

// 根 build.gradle
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

// module build.gradle

apply plugin: 'kotlin-android'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

这个时候配合着anko使用效果更好呦,只需要在build.gradle中进行相应的配置:

apply plugin: 'kotlin-android-extensions'
compile "org.jetbrains.anko:anko-sdk15:0.9.1"

就这么两行的配置即可告别findViewById的繁琐过程,目前这个项目对于ButterKnife的依赖我都去掉了,极其方便。

只要XML定义了"@+id/test",就可以直接引用这个View.

比如我的这个跳转界面SplashActivityXML

<ImageView
    android:id="@+id/iv_splash"
    android:background="?attr/colorPrimary"
    android:layout_centerInParent="true"
    android:src="@mipmap/ic_splash"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

代码中可以直接使用(属性动画):

val translationX: ObjectAnimator = ObjectAnimator.ofFloat(iv_splash, "translationX", 600f, 0f)
#rewardButton { background-color: #ea6f5a; } .btn-pay { margin-bottom: 20px; padding: 8px 25px; font-size: 16px; color: #fff; background-color: #ea6f5a; } .btn { display: inline-block; margin-bottom: 0; font-weight: 400; text-align: center; vertical-align: middle; touch-action: manipulation; cursor: pointer; background-image: none; border: 1px solid transparent; white-space: nowrap; padding: 6px 12px; font-size: 14px; line-height: 1.42857; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } #QR img{ height: 200px; height: 200px; margin: 20px; }
文章目录
  1. 1. 前言
  2. 2. 使用步骤
    1. 2.1. 1. Android Studio集成Kotlin插件
您是第 位小伙伴 | 本站总访问量 | 已经写了 120.4k 字啦

载入天数...载入时分秒...