Koltin 官方Android开源库 ANKO 详解 一

引言

anko 是kotlin官方(JetBrains)针对android快速开发 而开源的一个库,主要的目的是以代码取代xml来书写UI布局、包含了很多常用的函数和功能 以减少大量的模板代码(类似 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

常规代码如下:

val intent = Intent(this, SomeOtherActivity::class.java)
intent.putExtra("id", 5)
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)

anko代码

//等价于上面的常规代码
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
//传递单数据
startActivity<SomeOtherActivity>("id" to 5)
//传递多数据
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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容