当前位置: 首页 > 工具软件 > Anko > 使用案例 >

如何在Android中使用Kotlin Anko库

章玮
2023-12-01

In this tutorial, we’ll discuss the Kotlin Anko library. We’ll learn how to use the Anko Commons module in android apps.

在本教程中,我们将讨论Kotlin Anko库。 我们将学习如何在Android应用程序中使用Anko Commons模块。

Kotlin Anko图书馆 (Kotlin Anko Library)

Anko is an open-source Kotlin library that was developed by JetBrains for revolutionalizing the Android Development. It makes your code small and with the improved readability, it gets closer to English poetry.

Anko是由JetBrains开发的开源Kotlin库,用于彻底改变Android开发。 它使您的代码更小,并具有增强的可读性,使其更接近英语诗歌。

Anko was developed with the goal to extract the full benefits out of the Kotlin Syntax and make the Android Development faster and easier.

开发Anko的目的是从Kotlin语法中提取全部收益,并使Android开发更快,更轻松。

Anko组件 (Anko Components)

The Anko DSL library consists of the following components.

Anko DSL库由以下组件组成。

  • Anko Commons – This library consists of common tasks in android development. It provides helpers for intents, logging, alert dialogs, async, toasts etc.

    Anko Commons –该库包含android开发中的常见任务。 它为意图,日志记录,警报对话框,异步,敬酒等提供帮助。
  • Anko Layouts – Lets you quickly create layouts programmatically in a faster and easier way.

    Anko布局 –可让您以更快,更轻松的方式以编程方式快速创建布局。
  • Anko SQLite – This provides helper functions for Android SQLite

    Anko SQLite –为Android SQLite提供帮助功能
  • Anko Coroutine – It supplies utilities based on the kotlinx.coroutines library.

    Anko Coroutine –它基于kotlinx.coroutines库提供实用程序。

We’ll be concentrating on Anko Commons in this tutorial.

在本教程中,我们将专注于Anko Commons。

Anko Commons模块 (Anko Commons Module)

We have to add the following Gradle dependency to use Anko Commons module.

我们必须添加以下Gradle依赖项才能使用Anko Commons模块。

implementation 'org.jetbrains.anko:anko-commons:0.10.2'

If you want to use To use the Appcompat Styles, add the following dependency.

如果要使用若要使用Appcompat样式,请添加以下依赖项。

implementation 'org.jetbrains.anko:anko-appcompat-v7-commons:0.10.2'

Anko Commons示例 (Anko Commons Examples)

We will implement the following components in our android app.

我们将在我们的android应用中实现以下组件。

  • Toasts

    敬酒
  • Alert Dialogs

    警报对话框
  • Selectors

    选择器
  • Intents

    意向
  • Logging

    记录中
  • Miscelleaneous Helper Functions

    辅助功能

Let’s look at each of the utility helper functions one at a time.

让我们一次查看每个实用程序助手功能。

1.吐司 (1. Toasts)

val number = 1

toast("Hello Anko Commons")
toast(R.string.app_name)
longToast("Long Toast $number")

The above code creates helper functions for normal toast and long toast with respective time as Toast.LENGTH_SHORT and Toast.LENGTH_LONG.

上面的代码为普通吐司和长吐司创建了辅助函数,其时间分别为Toast.LENGTH_SHORTToast.LENGTH_LONG

Their equivalent non-anko code is:

其等效的非anko代码为:

Toast.makeText(applicationContext, "string", Toast.LENGTH_SHORT).show()
Toast.makeText(applicationContext, "string", Toast.LENGTH_LONG).show()

For more details on the non-Anko Android Toasts, refer this tutorial.

有关非Anko Android Toast的更多详细信息,请参阅本教程

2.警报对话框 (2. Alert Dialogs)

The Anko Commons utility function for displaying an alert dialog is:

用于显示警报对话框的Anko Commons实用程序功能是:

alert("You have a message!", "Android Anko Alert") {
                yesButton { toast("Yes") }
                noButton {}
                neutralPressed("Maybe") {}
            }.show()

Inside the alert block we can add the following properties too:

在警报块内,我们也可以添加以下属性:

  • message

    message
  • title

    title
  • icon

    icon
  • positiveButton

    positiveButton
  • negativeButton

    negativeButton
  • okButton

    okButton
  • cancelButton

    cancelButton
  • onCancelled{ }

    onCancelled{ }
  • customTitle{ } – Here we can add an Anko Layout for the title layout. We’ll look into this in the next tutorial.

    customTitle{ } –在这里,我们可以为标题布局添加customTitle{ }布局。 我们将在下一个教程中对此进行研究。
  • customView { } – Here we can set a custom view using Anko Layouts. More on this in the next tutorial.

    customView { } –在这里,我们可以使用Anko Layouts设置自定义视图。 在下一个教程中将对此进行更多介绍。

The non-Anko code for Alert Dialogs is:

警报对话框的非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.共用选择器 (3. Commons Selectors)

The syntax to add a list of items inside the Alert Dialog is as follows:

在“警报”对话框中添加项目列表的语法如下:

val languages = listOf("Java", "Python", "Kotlin", "Swift")
            selector("Your favourite programming language?", languages, { dialogInterface, i ->
                toast("You're favourite language is ${languages[i]}, right?")
            })

The Anko Commons Alert Dialog code is more concise then the non-Anko ones discussed here.

Anko Commons Alert对话框代码比此处讨论的非Anko更为简洁。

The equivalent generic code is:

等效的通用代码是:

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() (4. Anko doAsync())

We can use the doAsync() utility function to run a task in the background thread and switch back to the main thread.

我们可以使用doAsync()实用程序函数在后台线程中运行任务,然后切换回主线程。

doAsync{
 //implement background task here
   uiThread{
   //this thread is the main thread. update the UI here.
   }
}

5. Android Anko意图 (5. Android Anko Intents)

We can shorten our Intents code to start activities using Anko commons.

我们可以缩短Intents代码以使用Anko Commons开始活动。

The following is non-Anko code for Intents in Android.

以下是Android中Intent的非Anko代码。

val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)

Anko Commons Code:

Anko Commons代码:

startActivity<SecondActivity>()

Setting Flags and passing values

设置标志并传递值

Android Code:

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)

Anko Code:

安科代码:

startActivity(intentFor<SecondActivity>("value" to 3, "name" to "Androidly").singleTop())

We have to use intentFor to pass the flags.

我们必须使用intentFor来传递标志。

6.意向助手功能 (6. Intent Helper Functions)

  • makeCall(number) – Must ask for runtime permissions. We’ll cover this later.

    makeCall(number)–必须要求运行时权限。 我们稍后再讨论。
  • sendSMS(number, ) – Must add runtime permissions. We’ll cover this later.

    sendSMS(number,)–必须添加运行时权限。 我们稍后再讨论。
  • browse(url: String) – Must set Internet Permission

    Browse(URL:String)–必须设置Internet权限
  • share(text, [subject])

    分享(文本,[主题])
  • email(email, [subject], )

    电子邮件(电子邮件,[主题],)

We’ll implement many of these in our Android Studio Project later in this tutorial.

本教程稍后将在我们的Android Studio项目中实现其中的许多功能。

7. Anko记录 (7. Anko Logging)

Anko commons provide shorthand forms for various types of logging statements.

Anko Commons为各种类型的日志记录语句提供了简写形式。

The non-Anko version for debug log is:

调试日志的非Anko版本为:

Log.d("TAG","debug")

We have to implement the AnkoLogger interface in the Activity class. After that, call the logging functions as shown below.

我们必须在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")

Note that there are two styles of the above functions – () and {}

请注意,上述函数有两种样式-()和{}

8.杂项功能 (8. Miscellaneous Functions)

Some of the Anko Commons helper functions that are used for dimension conversions are:

用于尺寸转换的一些Anko Commons帮助器功能包括:

  • dip() – converts the Int or float passed into dip

    dip() –将传递的Int或float转换为dip
  • sp() – converts the Int or float passed into sp value

    sp() –将传递的Int或float转换为sp值
  • px2dip() – converts px to dip

    px2dip() –将px转换为dip
  • px2sp() – converts px to sp.

    px2sp() –将px转换为sp。

Android Anko示例项目结构 (Android Anko Example Project Structure)

Our Android Application will consist of two activities.

我们的Android应用程序将包含两个活动。

1. XML布局代码 (1. XML Layout Code)

The code for the layouts is given below:

布局的代码如下:

activity_main.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

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活动代码 (2. Kotlin Activity Code)

The code for the MainActivity.kt is given below.

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)
        }
    }
}

Inside the btnAdvAlertDialog function, we are creating another dialog when the dialog is cancelled on touching outside.

btnAdvAlertDialog函数内部,当触摸外部取消对话框时,我们正在创建另一个对话框。

We’ve also implemented the Alert Dialog differently. We are getting the AlertDialog instance and then making the changes.

我们还以不同的方式实现了“警报对话框”。 我们正在获取AlertDialog实例,然后进行更改。

The code for the SecondActivity.kt is given below.

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("anupamchugh@gmail.com (mailto:anupamchugh@gmail.com)", "Test Androidly", "Message text From Androidly Application")
        }



        btnShare.setOnClickListener {

            val number = 123
            share("Hello $number", "Copy")
        }
    }
}

Don’t forget to add the Internet Permission in your AndroidManifest.xml file.

不要忘记在您的AndroidManifest.xml文件中添加Internet权限。

Output:

输出:

翻译自: https://www.journaldev.com/307/kotlin-anko-android

 类似资料: