如何在Android中使用Kotlin Anko库
在本教程中,我们将讨论Kotlin Anko库。
我们将学习如何在Android应用中使用Anko Commons模块。
Kotlin Anko库
Anko是由JetBrains开发的开源Kotlin库,用于彻底改变Android开发。
它使您的代码更小,并具有增强的可读性,使其更接近英语诗歌。
开发Anko的目的是从Kotlin语法中提取全部收益,并使Android开发更快,更轻松。
Anko组件
Anko DSL库由以下组件组成。
Anko Commons –该库包含android开发中的常见任务。
它为意图,日志记录,警报对话框,异步,敬酒等提供帮助。Anko布局–可让您以更快,更轻松的方式以编程方式快速创建布局。
Anko SQLite –为Android SQLite提供帮助功能
Anko Coroutine –它基于
kotlinx.coroutines库提供实用程序。
在本教程中,我们将专注于Anko Commons。
Anko Commons模块
我们必须添加以下Gradle依赖项才能使用Anko Commons模块。
implementation 'org.jetbrains.anko:anko-commons:0.10.2'
如果要使用若要使用Appcompat样式,请添加以下依赖项。
implementation 'org.jetbrains.anko:anko-appcompat-v7-commons:0.10.2'
Anko Commons示例
我们将在我们的android应用中实现以下组件。
- Toasts
- Alert Dialogs
- Selectors
- Intents
- Logging
- 辅助功能
让我们一次查看每个实用程序助手功能。
1.Toasts
val number = 1
toast("Hello Anko Commons")
toast(R.string.app_name)
longToast("Long Toast $number")
上面的代码为普通吐司和长吐司创建了辅助函数,其时间分别为Toast.LENGTH_SHORT和Toast.LENGTH_LONG。
其等效的非anko代码为:
Toast.makeText(applicationContext, "string", Toast.LENGTH_SHORT).show() Toast.makeText(applicationContext, "string", Toast.LENGTH_LONG).show()
有关非Anko Android Toast的更多详细信息,请参阅本教程。
2.警报对话框
用于显示警报对话框的Anko Commons实用程序功能是:
alert("You have a message!", "Android Anko Alert") {
yesButton { toast("Yes") }
noButton {}
neutralPressed("Maybe") {}
}.show()
在警报块内,我们也可以添加以下属性:
消息
标题
iconpositiveButtonnegativeButton
ok按钮
cancelButton" onCancelled {}"
" customTitle {}" –其中我们可以为标题布局添加Anko Layout。
我们将在下一个教程中对此进行研究。customView {}–这里我们可以使用Anko Layouts设置自定义视图。
在下一个教程中将对此进行更多介绍。
警报对话框的非Anko代码是:
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK"){}
setNegativeButton(android.R.string.no){}
setNeutralButton("Maybe"){}
show()
}
3.共用选择器
在"警报"对话框中添加项目列表的语法如下:
val languages = listOf("Java", "Python", "Kotlin", "Swift")
selector("Your favourite programming language?", languages, { dialogInterface, i ->
toast("You're favourite language is ${languages[i]}, right?")
})
Anko Commons Alert对话框代码比此处讨论的非Anko更为简洁。
等效的通用代码是:
val items = arrayOf("Red", "Orange", "Yellow", "Blue")
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("List of Items")
setItems(items) { dialog, which ->
Toast.makeText(applicationContext, items[which] + " is clicked", Toast.LENGTH_SHORT).show()
}
setPositiveButton("OK", positiveButtonClick)
show()
}
4. Anko doAsync()
我们可以使用doAsync()实用程序函数在后台线程中运行任务,然后切换回主线程。
doAsync{
//implement background task here
uiThread{
//this thread is the main thread. update the UI here.
}
}
5. Android Anko意图
我们可以缩短Intents代码以使用Anko Commons开始活动。
以下是Android中Intent的非Anko代码。
val intent = Intent(this, SecondActivity::class.java) startActivity(intent)
Anko Commons代码:
startActivity<SecondActivity>()
设置标志并传递值
Android代码:
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("value", 3)
intent.putExtra("name", "Androidly")
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
安科代码:
startActivity(intentFor<SecondActivity>("value" to 3, "name" to "Androidly").singleTop())
我们必须使用" intentFor"来传递标志。
6.意向助手功能
makeCall(number)–必须要求运行时权限。
我们稍后会介绍。sendSMS(number,)–必须添加运行时权限。
我们稍后会介绍。Browse(URL:String)–必须设置Internet权限
分享(文字,[主题])
电子邮件(电子邮件,[主题],)
本教程稍后将在我们的Android Studio项目中实现其中许多功能。
7. Anko记录
Anko Commons为各种类型的日志记录语句提供了简写形式。
调试日志的非Anko版本是:
Log.d("TAG","debug")
我们必须在Activity类中实现AnkoLogger接口。
之后,如下所示调用日志记录功能。
info("Info log")
debug(5) //converts to string.
debug { "Each log can be written in either of these forms" }
warn(null) //shows null
verbose { "Verbose" }
wtf("Kotlin Androidly Tutorial")
请注意,上述函数有两种样式-()和{}
8.杂项功能
用于尺寸转换的一些Anko Commons帮助器功能包括:
dip()–将传递的Int或者float转换为dip- sp()–将传递的Int或者float转换为sp值
- px2dip()–将px转换为dip
- px2sp()–将px转换为sp。
Android Anko示例项目结构
我们的Android应用程序将包含两个活动。
1. XML布局代码
下面给出了布局的代码:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btnShortToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Short Toast"
<Button
android:id="@+id/btnLongToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long Toast"
<Button
android:id="@+id/btnSimpleAlertDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple Alert Dialog"
<Button
android:id="@+id/btnAdvAlertDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Advanced Alert Dialog"
<Button
android:id="@+id/btnAlertDialogWithList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog With List"
<Button
android:id="@+id/btnDoAsync"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DO ASYNC"
<Button
android:id="@+id/btnIntent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Goto Next Activity"
</LinearLayout>
activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".SecondActivity">
<Button
android:id="@+id/btnBrowseUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Browse Url"
<Button
android:id="@+id/btnSendEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Email"
<Button
android:id="@+id/btnShare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share"
</LinearLayout>
2. Kotlin活动代码
MainActivity.kt的代码如下。
package net.androidly.androidlyankocommons
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.Appcompat
class MainActivity : AppCompatActivity(), AnkoLogger {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
info("Info log")
debug(5)
debug { "Each log can be written in either of these forms" }
warn(null)
verbose { "Verbose" }
wtf("Kotlin Androidly Tutorial")
btnShortToast.setOnClickListener {
toast("Hello Anko Commons")
toast(R.string.app_name)
}
btnLongToast.setOnClickListener {
longToast("Long!")
}
btnSimpleAlertDialog.setOnClickListener {
alert("You have a message!", "Android Anko Alert") {
yesButton { toast("Yes") }
noButton {}
neutralPressed("Maybe") {}
}.show()
}
btnAdvAlertDialog.setOnClickListener {
alert("Anko Common Alert") {
title = "Title"
yesButton { toast("Yes") }
noButton { }
icon = ContextCompat.getDrawable(this@MainActivity, R.mipmap.ic_launcher)!!
onCancelled {
val dialog = alert(Appcompat) {
title = "Anko Alerts"
message = "Don't press outside the dialog to cancel me again :)"
okButton { toast(android.R.string.ok) }
}.build()
with(dialog)
{
show()
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(ctx, R.color.colorPrimary))
}
}
}.show()
}
btnAlertDialogWithList.setOnClickListener {
val languages = listOf("Java", "Python", "Kotlin", "Swift")
selector("Your favourite programming language?", languages, { dialogInterface, i ->
toast("Your favourite language is ${languages[i]}, right?")
})
}
btnDoAsync.setOnClickListener {
doAsync {
Thread.sleep(2000)
uiThread {
toast("This work is done after 2 seconds")
}
}
}
btnIntent.setOnClickListener {
startActivity<SecondActivity>("name" to "Androidly", "age" to 1)
}
}
}
在btnAdvAlertDialog函数中,当触摸外部对话框被取消时,我们正在创建另一个对话框。
我们还以其他方式实施了"警告对话框"。
我们正在获取AlertDialog实例,然后进行更改。
SecondActivity.kt的代码如下。
package net.androidly.androidlyankocommons
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_second.*
import org.jetbrains.anko.browse
import org.jetbrains.anko.email
import org.jetbrains.anko.share
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
btnBrowseUrl.setOnClickListener {
browse("https://www.androidly.net")
}
btnSendEmail.setOnClickListener {
email("[email protected] (mailto:[email protected])", "Test Androidly", "Message text From Androidly Application")
}
btnShare.setOnClickListener {
val number = 123
share("Hello $number", "Copy")
}
}
}
不要忘记在您的AndroidManifest.xml文件中添加Internet权限。

