使用 Kotlin 优雅地开发 Android 应用

MarlysAnder 7年前
   <p style="text-align:center"><img src="https://simg.open-open.com/show/01965b175b8bfb32f7580e92f3e21d53.png"></p>    <p><a href="/misc/goto?guid=4959748795438722813" rel="nofollow,noindex">代码传送门</a></p>    <h2>写在前面</h2>    <p>在之前的一篇文章,我们简单的知道了Kotlin这门新语言的优势,也接触了一些常见的语法及其简单的使用,相信你会对它有浓厚的兴趣,暂且理解为对它感兴趣吧,哈哈哈。那么,我们该如何在Android中应用这门新的语言呢?今天的这篇文章带你学习使用Kotlin开发Android应用,并对比我们传统语言Java,让你真真切切的感受到他的美和优雅。</p>    <h2>配置</h2>    <p>项目gradle文件</p>    <pre>  <code class="language-java">apply plugin: 'com.android.application'  apply plugin:'kotlin-android'  apply plugin:'kotlin-android-extensions'    dependencies {      classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.1'  }</code></pre>    <p>app Gradle文件:</p>    <pre>  <code class="language-java">compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.1'  compile 'org.jetbrains.anko:anko-sdk25:0.10.0-beta-1'// sdk15, sdk19, sdk21, sdk23 are also available  compile 'org.jetbrains.anko:anko-appcompat-v7:0.10.0-beta-1'</code></pre>    <h2>Anko</h2>    <p>通过上面的配置,你会发现引入的有anko的依赖。Anko是JetBrains开发的一个强大的库,说起JetBrains ,那就牛逼了,Kotlin语言是他们开发的,最流行的的开发工具intellij idea都是他们开发的,AS也是基于IDEA的。好了,言归正传,Anko是Kotlin官方开发的一个让开发Android应用更快速更简单的Kotlin库,并且能让我们书写的代码更简单清楚更容易阅读。它包括多个部分,如下</p>    <pre>  <code class="language-java">Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on;  Anko Layouts: a fast and type-safe way to write dynamic Android layouts;  Anko SQLite: a query DSL and parser collection for Android SQLite;  Anko Coroutines: utilities based on the kotlinx.coroutines library</code></pre>    <p>那么接下来,我们就通过代码来理解Kotlin语言开发Android的优势所在。</p>    <h2>再也不用findViewById</h2>    <p>做过Android开发的人都知道,布局文件写的多了,findViewById也是一个很大的工作量,而且还要先声明变量,在findViewById然后再强转成我们的控件,使用方式一般如下</p>    <pre>  <code class="language-java">TextView username;  username=(TextView)findViewById(R.id.user);    username.setText("我是一个TextView");</code></pre>    <p>有时候写的是不是想吐,可能有些人说现在不是有一些注解的库,如butterknife,当我们使用注解时可以不用findViewById了,使用方式如下</p>    <pre>  <code class="language-java">@BindView(R.id.user)  TextView username;    username.setText("我是一个TextView");</code></pre>    <p>确实是这样,使用注解后确实给我们少了一些工作量,不过这依然没有最简单化,最简单的就是我们可以直接给id为user的控件直接赋值,或许你会感觉这有点不可思议。不过Kotlin确实做到了。我们可以直接这样写</p>    <pre>  <code class="language-java">user.text="我是一个TextView"</code></pre>    <p>看到这你是不是有一种相见恨晚的感觉,太Tama的简洁了。user就是我们布局文件声明的id,.text就想当与setText()给,在Kotlin语言中,我们看不到了像Java中的set/get方法了。需要注意的时,当我没呢这样使用,需要加入下面一句代码</p>    <pre>  <code class="language-java">//activity_login就是我们的布局  import kotlinx.android.synthetic.main.activity_login.*</code></pre>    <h2>Anko Layout</h2>    <p>通常我们使用xml文件写我们的布局,但是他有一些缺点如不是类型安全,不是空安全,解析xml文件消耗更多的CPU和电量等等。而Anko Layout可以使用DSL动态创建我们的UI,并且它比我们使用Java动态创建布局方便很多主要是更简洁,它和拥有xml创建布局的层级关系,能让我们更容易阅读。</p>    <pre>  <code class="language-java">verticalLayout {              val textView=textView("我是一个TextView")              val name = editText("EditText")              button("Button") {                  onClick { toast("${name.text}!") }              }          }</code></pre>    <p>我们在OnCreate方法中可以去掉setContentView,然后加入上面代码就可以显示如下图的效果,即一个垂直的线性布局中,放了一个TextView,一个EditText,和一个Button。并且Button中有一个点击事件,当点击时将EditText的内容</p>    <p>以toast显示。</p>    <p><img src="https://simg.open-open.com/show/b73d22bbe3744309a47f05b82914fc19.png"></p>    <p>上面的代码是不是很简单易懂,当然,默认的控件并不能满足我们的需求,例如我们会更改字体的颜色及大小,会设置宽度和高度,会设置margin,padding值,那么该如何实行呢,当然也很简单,因为它的逻辑和xml书写布局是一个套路。例如以下实现</p>    <pre>  <code class="language-java">val textView=textView("我是一个TextView"){                  textSize = sp(17).toFloat()                  textColor=context.resources.getColor(R.color.red)              }.lparams{                  margin=dip(10)                  height= dip(40)                  width= matchParent              }</code></pre>    <p>我想我不需要说明上面的代码,你就应该看得出控件实行的效果。因为它的属性和我们在xml设置属性的名字对应的。</p>    <p>在上面创建UI过程中,我们直接把创建UI的代码写在onCreate方法中了,当然,还有一种写法。我们创建一个内部类实行AnkoComponent接口,并重写createView方法,该方法返回一个View,也就是我们创建的布局。修改如下</p>    <pre>  <code class="language-java">inner class UI : AnkoComponent<LoginActivity> {          override fun createView(ui: AnkoContext<LoginActivity>): View {             return with(ui){                 verticalLayout {                     val textView=textView("我是一个TextView"){                         textSize = sp(17).toFloat()                         textColor=context.resources.getColor(R.color.red)                     }.lparams{                         margin=dip(10)                         height= dip(40)                         width= matchParent                     }                     val name = editText("EditText")                     button("Button") {                          onClick { view ->                              toast("Hello, ${name.text}!")                          }                     }                 }             }          }      }</code></pre>    <p>然后在onCreate方法中加一句代码,即可创建我们的布局页面了。如下</p>    <pre>  <code class="language-java">UI().setContentView(this@LoginActivity)</code></pre>    <p>现在我们编译运行,发现效果和布局文件写的界面是一样的。但是它的性能是有优势的,其实吧并没有发觉性能优势。不管怎样,这种DSL确实便于阅读,也很容易上手,在上面的代码中,你可能注意到了dip(10),它表示将10dp转换为像素的意思,是Anko的扩展函数,说的扩展函数,如果阅读过Anko的源码我们发现里面大量的使用扩展函数,这也是Kotlin语言的优势之一。确实很强大,例如dip扩展(摘取View扩展)</p>    <pre>  <code class="language-java">inline fun View.dip(value: Int): Int = context.dip(value)  fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()</code></pre>    <p>在上面resources.displayMetrics.density和我们Java getResources().getDisplayMetrics().density是一个效果,不过看着你会不会感觉比Java书写舒服多了,反正我是这么感觉的。</p>    <p>在上面的我们给Button加了一个点击事件,我们发现它支持lambda表达式。我们想显示一个Toast,只需要toast("内容")就可以了,是不是又很简洁。其实它也是扩展函数,实现</p>    <pre>  <code class="language-java">inline fun AnkoContext<*>.toast(message: CharSequence) = ctx.toast(message)  fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()</code></pre>    <p>当然创建dialog依然也很简单,如下</p>    <pre>  <code class="language-java">alert ("我是Dialog"){                        yesButton { toast("yes")}                        noButton {  toast("no")}                      }.show()</code></pre>    <p>真是越看越舒心,哈哈。再来一个强大而又很简单很简单很简洁的一段代码实现。</p>    <pre>  <code class="language-java">doAsync {              //后台执行代码              uiThread {               //UI线程              toast("线程${Thread.currentThread().name}") }          }</code></pre>    <p>该段代码实现的就是AsyncTask 的效果,但是你应该发现它比Java的实现简洁多了,当然除非是色盲,要不然你会看出简洁的。</p>    <p>如果你使用Kotlin开发Android一段时间后,会发现它给我们减少了很多的代码量,当然更多的优势及用法需要我们自己去探索。相信经过探索后它会让你大吃一惊。</p>    <h2>实现一个简单的登录界面</h2>    <p><img src="https://simg.open-open.com/show/2d699eb11a8f0b1e05e68a8b63b7699b.png"></p>    <p>界面很简单,伪代码</p>    <pre>  <code class="language-java"><LinearLayout>    <ImageView/>    <LinearLayout> <ImageView/><EditText账号/><LinearLayout>    <LinearLayout> <ImageView/><EditText密码/><LinearLayout>    <Button 登录/>    <LinearLayout> <CheckBox 记住密码/><TextView 隐私协议xieu/><LinearLayout>    <TextView/>    </LinearLayout></code></pre>    <p>看着并不复杂的,那么xml实现的代码就不在这贴出了,如果你想看xml实现可看 <a href="/misc/goto?guid=4959748795519133767" rel="nofollow,noindex">点击查</a> ,那么接下来来只看Anko在Kotlin代码中实现这个布局。</p>    <pre>  <code class="language-java">lateinit var et_account: EditText      lateinit var et_password: EditText      inner class LoginUi : AnkoComponent<LoginActivity> {          override fun createView(ui: AnkoContext<LoginActivity>) = with(ui) {              verticalLayout {                  backgroundColor = context.resources.getColor(android.R.color.white)                  gravity = Gravity.CENTER_HORIZONTAL                  imageView(R.mipmap.ic_launcher).lparams {                      width = dip(100)                      height = dip(100)                      topMargin = dip(64)                  }                    linearLayout {                      gravity = Gravity.CENTER_VERTICAL                      orientation = HORIZONTAL                      backgroundResource = R.drawable.bg_frame_corner                      imageView {                          image = resources.getDrawable(R.mipmap.ic_username)                      }.lparams(width = wrapContent, height = wrapContent) {                          leftMargin = dip(12)                          rightMargin = dip(15)                      }                      et_account = editText {                          hint = "登录账户"                          hintTextColor = Color.parseColor("#666666")                          textSize = 16f                          background = null                      }                  }.lparams(width = dip(300), height = dip(40)) {                      topMargin = dip(45)                  }                    linearLayout {                      orientation = HORIZONTAL                      backgroundResource = R.drawable.bg_frame_corner                      gravity = Gravity.CENTER_VERTICAL                      imageView {                          image = resources.getDrawable(R.mipmap.ic_password)                      }.lparams {                          leftMargin = dip(12)                          rightMargin = dip(15)                      }                      et_password = editText {                          hint = "登录密码"                          hintTextColor = Color.parseColor("#666666")                          textSize = 16f                          background = null                      }                  }.lparams {                      width = dip(300)                      height = dip(40)                      topMargin = dip(10)                    }                    button("登录") {                      gravity = Gravity.CENTER                      background = resources.getDrawable(R.drawable.bg_login_btn)                      textColor = Color.parseColor("#ffffff")                      onClick {                          if (et_account.text.toString().isNotEmpty() && et_password.text.toString().isNotEmpty())                              startActivity<MainActivity>() else toast("请输入账户或者密码")                      }                  }.lparams(width = dip(300), height = dip(44)) {                      topMargin = dip(18)                  }                  linearLayout {                      orientation = HORIZONTAL                      gravity = Gravity.CENTER_VERTICAL                      checkBox("记住密码") {                          textColor = Color.parseColor("#666666")                          textSize = 16f                          leftPadding = dip(5)                      }                      textView("隐私协议") {                          textColor = Color.parseColor("#1783e3")                          gravity = Gravity.RIGHT                          textSize = 16f                      }.lparams(width = matchParent)                  }.lparams(width = dip(300)) {                      topMargin = dip(18)                  }                    textView("Copyright © Code4Android") {                      textSize = 14f                      gravity = Gravity.CENTER or Gravity.BOTTOM                    }.lparams {                      bottomMargin = dip(35)                      weight = 1f                  }              }          }      }</code></pre>    <p>看到上面的代码怎么样,看起来还不错吧,即使现在你不会写,但是你也能读懂它。在上面我们给登录按钮设置一个打开MainActivity的事件。startActivity的<>中写的是我们要跳转的Activity,如果给打开的界面传递参数,直接写在()中。例如我们将输入的账号和密码传到跳转的界面,则实现为</p>    <pre>  <code class="language-java">startActivity<MainActivity>("account" to et_account.text.toString(),"password" to et_password.text.toString())</code></pre>    <p>其实Anko的强大之处远不止于此,值得我们细细品味。想更深入学习可以去 <a href="/misc/goto?guid=4959668049818350775" rel="nofollow,noindex">GitHub Anko</a> ,到此呢,本篇文章也就结束了,若在阅读时发现错误之处,欢迎指出,谢谢,Have a wonderful day.</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/4f60932d46ff</p>    <p> </p>