前言
之前写了一写Kotlin的基本操作 是不是感觉太好用了
但是接下来介绍的这个库 让你会觉得太爽了 这个库就是超级好用的库anko
它总共有四个部分
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.
这里我们先说Anko Commons
它的作用
引用
1 | dependencies { |
异步操作
1 | doAsync { |
Intent
原写法
1 | var intent = Intent(); |
新写法
1 | var intent = intentFor<SMainActivity>("id" to 5,"name" to "zhangjian").clearTask().newTask() |
其他有用的Intent
作用 | 写法 |
---|---|
打电话 | makeCall(number) without tel: |
发短信 | sendSMS(number, [text]) without sms: |
打开网页 | browse(url) |
分享文字 | share(text, [subject]) |
发邮件 | email(email, [subject], [text]) |
参数 ([]
) 是可选的. 如果intent
成功发送 方法返回true
.
Dialogs and toasts
引用
1 | dependencies { |
使用方式
Toasts
Simply shows a Toast message.
1 | toast("Hi there!") |
SnackBars
Simply shows a SnackBar message.
1 | snackbar(view, "Hi there!") |
Alerts
A small DSL for showing alert dialogs.
1 | alert("Hi, I'm Roy", "Have you tried turning it off and on again?") { |
The code above will show the default Android alert dialog. If you want to switch to the appcompat implementation, use the Appcompat
dialog factory:
1 | alert(Appcompat, "Some text message").show() |
Android
and Appcompat
dialog factories are included by default, but you can create your custom factories by implementing the AlertBuilderFactory
interface.
alert()
functions seamlessly support Anko layouts as custom views:
1 | alert { |
Selectors
selector()
shows an alert dialog with a list of text items:
1 | val countries = listOf("Russia", "USA", "Japan", "Australia") |
Progress dialogs
progressDialog()
creates and shows a progress dialog.
1 | val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data") |
Logging
使用方式
1 | info("London is the capital of Great Britain") |
对比
android.util.Log | AnkoLogger |
---|---|
v() |
verbose() |
d() |
debug() |
i() |
info() |
w() |
warn() |
e() |
error() |
wtf() |
wtf() |
默认的
tag
是类名Lambda result will be calculated only if
Log.isLoggable(tag, Log.INFO)
istrue
.
自定义tag
1 | class SomeActivity : Activity() { |
Resources and dimensions
这部分总体感觉没什么卵用
Colors
Two simple extension functions to make the code more readable.
Function | Result |
---|---|
0xff0000.opaque |
non-transparent red |
0x99.gray.opaque |
non-transparent #999999 gray |
Dimensions
px转dp/sp
1 | px2dip(10) |
applyRecursively()
applyRecursively()
applies the lambda expression to the passed View
itself, and then recursively to every child of a View
if it is a ViewGroup
:
1 | verticalLayout { |