引言
anko 是kotlin官方(JetBrains)針對(duì)android快速開發(fā) 而開源的一個(gè)庫樊拓,主要的目的是以代碼取代xml來書寫UI布局、包含了很多常用的函數(shù)和功能 以減少大量的模板代碼(類似 android官方的 各種 ktx 庫),本文主要介紹后者
Anko Commons – Dialogs
- implementation
dependencies {
implementation "org.jetbrains.anko:anko-commons:$anko_version"
implementation "org.jetbrains.anko:anko-design:$anko_version" // For SnackBars
}
- toast
toast("Hi there!")
toast(R.string.message)
longToast("Wow, such duration")
- SnackBars
view.snackbar("Hi there!")
view.snackbar(R.string.message)
view.longSnackbar("Wow, such duration")
view.snackbar("Action, reaction", "Click me!") { doStuff() }
- Alerts
alert("Hi, I'm Roy", "Have you tried turning it off and on again?") {
yesButton { toast("Oh…") }
noButton {}
}.show()
alert(Appcompat, "Some text message").show()
- Selectors
val countries = listOf("a", "b", "c", "d")
selector("Where are you from?", countries, { dialogInterface, i ->
toast("So you're living in ${countries[i]}, right?")
})
- Progress dialogs
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
Anko Coroutines(線程切換)
- implementation
dependencies {
implementation "org.jetbrains.anko:anko-coroutines:$anko_version"
}
Anko Commons – Intents
- implementation
dependencies {
implementation "org.jetbrains.anko:anko-commons:$anko_version"
}
- startActivity
常規(guī)代碼如下:
val intent = Intent(this, SomeOtherActivity::class.java)
intent.putExtra("id", 5)
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
anko代碼
//等價(jià)于上面的常規(guī)代碼
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
//傳遞單數(shù)據(jù)
startActivity<SomeOtherActivity>("id" to 5)
//傳遞多數(shù)據(jù)
startActivity<SomeOtherActivity>(
"id" to 5,
"city" to "Denpasar"
)
- Make a call
makeCall(number) // without tel
- send sms
sendSMS(number, [text]) //without sms
- Browse
browse(url)