您的位置:首页 > 移动开发 > Android开发

Kotlin简单实用方法既使用Kotlin优雅的开发Android应用

2017-06-28 11:53 666 查看
2017谷歌I/O全球开发者大会,于2017年5月17日至19日在美国加州山景城海岸线圆形剧场(Shoreline Amphitheatre)举行。谷歌在本次大会上充分介绍了人工智能在各个领域的应用,还推出iOS版语音助手、Android
O最新版本和VR眼镜系列,最主要的一项就是在这次Google  I/O大会上,提出将Kotlin编程语言作为Android开发一级语言,这门语言在2010年就已经开始对外开源,可是Google直到今年的I/O大会上才提出将其作为Android客户端开发的一级语言,想必Google也是有一定的想法的吧!

今天的这篇文章带你学习使用Kotlin开发Android应用,并对比我们传统语言Java,让你真真切切的感受到他的美和优雅。


配置

项目gradle文件
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'
}


app Gradle文件:
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'

Anko

通过上面的配置,你会发现引入的有anko的依赖。Anko是JetBrains开发的一个强大的库,说起JetBrains ,那就牛逼了,Kotlin语言是他们开发的,最流行的的开发工具intellij idea都是他们开发的,AS也是基于IDEA的。好了,言归正传,Anko是Kotlin官方开发的一个让开发android应用更快速更简单的Kotlin库,并且能让我们书写的代码更简单清楚更容易阅读。它包括多个部分,如下
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
那么接下来,我们就通过代码来理解Kotlin语言开发Android的优势所在。

再也不用findViewById

做过Android开发的人都知道,布局文件写的多了,findViewById也是一个很大的工作量,而且还要先声明变量,在findViewById然后再强转成我们的控件,使用方式一般如下
TextView username;
username=(TextView)findViewById(R.id.user);

username.setText("我是一个TextView");
有时候写的是不是想吐,可能有些人说现在不是有一些注解的库,如butterknife,当我们使用注解时可以不用findViewById了,使用方式如下
@BindView(R.id.user)
TextView username;

username.setText("我是一个TextView");
确实是这样,使用注解后确实给我们少了一些工作量,不过这依然没有最简单化,最简单的就是我们可以直接给id为user的控件直接赋值,或许你会感觉这有点不可思议。不过Kotlin确实做到了。我们可以直接这样写
user.text="我是一个TextView"
看到这你是不是有一种相见恨晚的感觉,太Tama的简洁了。user就是我们布局文件声明的id,.text就想当与setText()给,在Kotlin语言中,我们看不到了像Java中的set/get方法了。需要注意的是,当我们想这样使用的时候(不用findViewById,直接使用xml控件我们需要在gradle加入apply plugin: 'kotlin-android-extensions'),需要加入下面一句代码
//activity_login就是我们的布局
import kotlinx.android.synthetic.main.activity_login.*

Anko Layout

通常我们使用xml文件写我们的布局,但是他有一些缺点如不是类型安全,不是空安全,解析xml文件消耗更多的CPU和电量等等。而Anko Layout可以使用DSL动态创建我们的UI,并且它比我们使用Java动态创建布局方便很多主要是更简洁,它和拥有xml创建布局的层级关系,能让我们更容易阅读。
verticalLayout {
val textView=textView("我是一个TextView")
val name = editText("EditText")
button("Button") {
onClick { toast("${name.text}!") }
}
}
我们在OnCreate方法中可以去掉setContentView,然后加入上面代码就可以显示如下图的效果,即一个垂直的线性布局中,放了一个TextView,一个EditText,和一个Button。并且Button中有一个点击事件,当点击时将EditText的内容
以toast显示。


上面的代码是不是很简单易懂,当然,默认的控件并不能满足我们的需求,例如我们会更改字体的颜色及大小,会设置宽度和高度,会设置margin,padding值,那么该如何实行呢,当然也很简单,因为它的逻辑和xml书写布局是一个套路。例如以下实现
val textView=textView("我是一个TextView"){
textSize = sp(17).toFloat()
textColor=context.resources.getColor(R.color.red)
}.lparams{
margin=dip(10)
height= dip(40)
width= matchParent
}
我想我不需要说明上面的代码,你就应该看得出控件实行的效果。因为它的属性和我们在xml设置属性的名字对应的。在上面创建UI过程中,我们直接把创建UI的代码写在onCreate方法中了,当然,还有一种写法。我们创建一个内部类实行AnkoComponent接口,并重写createView方法,该方法返回一个View,也就是我们创建的布局。修改如下
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}!")
}
}
}
}
}
}
然后在onCreate方法中加一句代码,即可创建我们的布局页面了。如下
UI().setContentView(this@LoginActivity)
现在我们编译运行,发现效果和布局文件写的界面是一样的。但是它的性能是有优势的,其实吧并没有发觉性能优势。不管怎样,这种DSL确实便于阅读,也很容易上手,在上面的代码中,你可能注意到了dip(10),它表示将10dp转换为像素的意思,是Anko的扩展函数,说的扩展函数,如果阅读过Anko的源码我们发现里面大量的使用扩展函数,这也是Kotlin语言的优势之一。确实很强大,例如dip扩展(摘取View扩展)
inline fun View.dip(value: Int): Int = context.dip(value)
fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()
在上面resources.displayMetrics.density和我们Java getResources().getDisplayMetrics().density是一个效果,不过看着你会不会感觉比Java书写舒服多了,反正我是这么感觉的。在上面的我们给Button加了一个点击事件,我们发现它支持lambda表达式。我们想显示一个Toast,只需要toast("内容")就可以了,是不是又很简洁。其实它也是扩展函数,实现
inline fun AnkoContext<*>.toast(message: CharSequence) = ctx.toast(message)
fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
当然创建dialog依然也很简单,如下
alert ("我是Dialog"){
yesButton { toast("yes")}
noButton {  toast("no")}
}.show()
真是越看越舒心,哈哈。再来一个强大而又很简单很简单很简洁的一段代码实现。
doAsync {
//后台执行代码
uiThread {
//UI线程
toast("线程${Thread.currentThread().name}") }
}
该段代码实现的就是AsyncTask 的效果,但是你应该发现它比Java的实现简洁多了,当然除非是色盲,要不然你会看出简洁的。如果你使用Kotlin开发Android一段时间后,会发现它给我们减少了很多的代码量,当然更多的优势及用法需要我们自己去探索。相信经过探索后它会让你大吃一惊。

实现一个简单的登录界面


界面很简单,伪代码
<LinearLayout>

<ImageView/>

<LinearLayout> <ImageView/><EditText账号/><LinearLayout>

<LinearLayout> <ImageView/><EditText密码/><LinearLayout>

<Button 登录/>

<LinearLayout> <CheckBox 记住密码/><TextView 隐私协议xieu/><LinearLayout>

<TextView/>

</LinearLayout>
看着并不复杂的,那么xml实现的代码就不在这贴出了,如果你想看xml实现可看点击查,那么接下来来只看Anko在Kotlin代码中实现这个布局。
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
}
}
}
}
看到上面的代码怎么样,看起来还不错吧,即使现在你不会写,但是你也能读懂它。在上面我们给登录按钮设置一个打开MainActivity的事件。startActivity的<>中写的是我们要跳转的Activity,如果给打开的界面传递参数,直接写在()中。例如我们将输入的账号和密码传到跳转的界面,则实现为
startActivity<MainActivity>("account" to et_account.text.toString(),"password" to et_password.text.toString())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: