使用 Kotlin 優雅的開發 Android 應用

來源:互聯網
上載者:User

標籤:beta   傳送門   help   copyright   center   match   介面   attribute   而且   

代碼傳送門寫在前面

在之前的一篇文章,我們簡單的知道了Kotlin這門新語言的優勢,也接觸了一些常見的文法及其簡單的使用,相信你會對它有濃厚的興趣,暫且理解為對它感興趣吧,哈哈哈。那麼,我們該如何在Android中應用這門新的語言呢?今天的這篇文章帶你學習使用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 availablecompile ‘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())

其實Anko的強大之處遠不止於此,值得我們細細品味。想更深入學習可以去GitHub Anko,到此呢,本篇文章也就結束了,若在閱讀時發現錯誤之處,歡迎指出,謝謝,Have a wonderful day.

使用 Kotlin 優雅的開發 Android 應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.