Android Toast is a UI widget that pops up on the screen for some time. It’s very similar to a notification, alert, or tooltip message. In this tutorial, we’ll learn how to create a Toast using Kotlin programming language.

Android Toast是一个UI小部件,它会在屏幕上弹出一段时间。 它与通知,警报或工具提示消息非常相似。 在本教程中,我们将学习如何使用Kotlin编程语言创建Toast。

何时在Android应用中使用Toasts? (When to use Toasts in Android app?)

Toast messages are used to show the user something that isn’t critical but might help the user with what’s happening in the application currently. For example, giving a hint for a specific field in the form.

Toast消息用于向用户显示不重要的内容,但可能会帮助用户了解应用程序中当前发生的情况。 例如,为表单中的特定字段提供提示。

创建吐司的语法 (Syntax to Create a Toast)

We can use the Toast class to create a toast message.

我们可以使用Toast类创建一条Toast消息。

Toast.makeText(this, "Androidly Short Toasts", Toast.LENGTH_SHORT).show();Toast.makeText(this, "Androidly Long Toasts", Toast.LENGTH_LONG).show();

Toast requires three arguments.

吐司需要三个参数。

  1. Context语境
  2. Message信息
  3. Duration持续时间

The show() function is used to display the Toast on the screen.

show()函数用于在屏幕上显示Toast。

We can customize the layout of the toast as well as its duration.

我们可以自定义吐司的布局及其持续时间。

使用Kotlin的Android Toast (Android Toast using Kotlin)

Let’s use the Kotlin to create an android app and create some toast messages.

让我们使用Kotlin创建一个android应用程序并创建一些Toast消息。

First of all, create a new Android Studio Project and include the Kotlin support if you’re using Android Studio 3.0.

首先,如果您使用的是Android Studio 3.0,请创建一个新的Android Studio项目并包括Kotlin支持。

Select an empty activity.

选择一个空的活动。

The custom_toast_layout.xml is used to define a custom layout for the Toast.

custom_toast_layout.xml用于定义Toast的自定义布局。

The layout for our activity_main.xml file is given in the following code snippet.

以下代码段给出了我们activity_main.xml文件的布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"><Buttonandroid:id="@+id/btnShortToast"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="SHORT TOAST"/><Buttonandroid:id="@+id/btnLongToast"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="LONG TOAST"/><Buttonandroid:id="@+id/btnCustomToast"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="CUSTOM TOAST"/></LinearLayout>

We’ve created three Buttons in our activity layout.

我们在活动布局中创建了三个按钮。

The toasts would behave differently on clicking each of the buttons.

吐司在单击每个按钮时的行为会有所不同。

The earlier mentioned Toast invocation looks a little verbose.

前面提到的Toast调用看起来有些冗长。

Let’s use Kotlin Extensions to create some dynamic toast messages.

让我们使用Kotlin Extensions创建一些动态的Toast消息。

烤面包的Kotlin扩展功能 (Kotlin Extension Functions for Toasts)

We can shorten our Toast invocation by setting some default values in the Kotlin extension functions.

我们可以通过在Kotlin扩展功能中设置一些默认值来缩短Toast调用。

The following function is an extension function that shall be used in our MainActivity.kt.

以下函数是应在我们的MainActivity.kt中使用的扩展函数。

fun Context.toast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_SHORT){Toast.makeText(context, message , duration).show()}

We’ve set the default values of context and duration. If you call toast("Message"), it will trigger the toast message.

我们设置了上下文和持续时间的默认值。 如果您调用toast("Message") ,它将触发toast消息。

The applicationContext represents the context of the application. It makes the toast visible throughout the application. We can always change the default value to a different context(example: Activity context or a Fragment’s context). The applicationContext is the equivalent of getApplicationContext() in Java.

applicationContext表示applicationContext的上下文。 它使吐司在整个应用程序中可见。 我们总是可以将默认值更改为其他上下文(例如:活动上下文或Fragment的上下文)。 applicationContext与Java中的getApplicationContext()等效。

如何从strings.xml设置祝酒消息? (How to set a toast message from strings.xml?)

String resources are of the type Int. So we need to set the parameter type as an Int.

字符串资源的类型为Int。 因此,我们需要将参数类型设置为Int。

The following extension function shows how to set strings.xml resource on a Toast.

以下扩展功能显示了如何在Toast上设置strings.xml资源。

fun Context.stringResToast(context: Context = applicationContext, message: Int, toastDuration: Int = Toast.LENGTH_SHORT) {Toast.makeText(context, context.getString(message), toastDuration).show()}

To trigger the Toast, we just need to pass the string resource inside the function in our activity.

要触发Toast,我们只需要在活动中的函数内部传递字符串资源即可。

stringResToast(message = R.string.app_name)

以编程方式创建吐司 (Creating a Toast Programmatically)

To create a Custom Toast programmatically we use a custom layout.

要以编程方式创建“自定义吐司”,我们使用自定义布局。

Following is the custom layout defined:

以下是定义的自定义布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/custom_toast_container"android:layout_width="match_parent"android:layout_height="48dp"android:background="#EAA"android:orientation="horizontal"android:padding="8dp"android:weightSum="1"><ImageViewandroid:id="@+id/imageView"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:layout_weight="0.2" /><TextViewandroid:id="@+id/textView"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_gravity="center_vertical"android:layout_weight="0.8"android:textColor="#FFF" />
</LinearLayout>

To instantiate a Toast programmatically, we do val toast = Toast(this), where this is the Context.

为了以编程方式实例化Toast,我们执行val toast = Toast(this) ,这是Context

Toasts are not views. Hence they can’t be added in the parent view using addView(). We need to inflate them.

吐司不是风景。 因此,不能使用addView()将它们添加到父视图中。 我们需要给它们inflate

The following function is used to create and trigger a Toast programmatically.

以下功能用于以编程方式创建和触发Toast。

fun createCustomToast(message: String, imageSrc: Int) {val toast = Toast(this)toast.apply {val layout = linearLayout.inflate(R.layout.custom_toast_layout)layout.textView.text = messagelayout.imageView.setBackgroundResource(imageSrc)setGravity(Gravity.CENTER, 0, 0)duration = Toast.LENGTH_SHORTview = layoutshow()}}fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)}

We’ve created an inflate function to shorten our Toast layout declaration.

我们创建了一个inflate函数来缩短Toast布局声明。

In the apply lambda expression, we inflate the layout in our Activity’s parent view using the inflate function.

在apply lambda表达式中,我们使用inflate函数在Activity的父视图中为布局充气。

Also, we set the text, image resource, duration as well as the gravity of the Toast.

另外,我们设置文本,图像资源,持续时间以及Toast的重力。

The setGravity requires us to set the Gravity type: LEFT, RIGHT, CENTER, CENTER_HORIZONTAL, CENTER VERTICAL.

setGravity要求我们设置Gravity类型:LEFT,RIGHT,CENTER,CENTER_HORIZONTAL,CENTER VERTICAL。

The second and third arguments are x and y offsets from the current position on the screen.

第二个和第三个参数是屏幕上当前位置的x和y偏移量。

The show() function triggers the Toast onto the screen.

show()函数将Toast触发到屏幕上。

Kotlin吐司代码– MainActivity.kt (Kotlin Toast Code – MainActivity.kt)

The code for the MainActivity.kt Kotlin’s class is given below.

下面给出了MainActivity.kt Kotlin类的代码。

package net.androidly.androidlytoastsimport android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.custom_toast_layout.view.*class MainActivity : AppCompatActivity(), View.OnClickListener {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)btnShortToast.setOnClickListener(this)btnLongToast.setOnClickListener(this)btnCustomToast.setOnClickListener(this)}override fun onClick(v: View?) {when (v?.id) {R.id.btnShortToast -> {toast(message = "Androidly Short Toasts")stringResToast(message = R.string.app_name)}R.id.btnLongToast -> {toast(message = "Androidly Long Toasts", toastDuration = Toast.LENGTH_LONG)}R.id.btnCustomToast -> {createCustomToast(message = "Androidly Custom Toast", imageSrc = R.mipmap.ic_launcher_round)}}}fun createCustomToast(message: String, imageSrc: Int) {val toast = Toast(this)toast.apply {val layout = linearLayout.inflate(R.layout.custom_toast_layout)layout.textView.text = messagelayout.imageView.setBackgroundResource(imageSrc)setGravity(Gravity.CENTER, 0, 0)duration = Toast.LENGTH_SHORTview = layoutshow()}}fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)}fun Context.toast(context: Context = applicationContext, message: String, toastDuration: Int = Toast.LENGTH_SHORT) {Toast.makeText(context, message, toastDuration).show()}fun Context.stringResToast(context: Context = applicationContext, message: Int, toastDuration: Int = Toast.LENGTH_SHORT) {Toast.makeText(context, context.getString(message), toastDuration).show()}}

In the above code, we’ve implemented the View.OnClickListener interface.

在上面的代码中,我们已经实现了View.OnClickListener接口。

We’ve used a when statement to detect which button is clicked.

我们使用了when语句来检测单击了哪个按钮。

On the Button clicks, we display the specific Toasts that were defined in the earlier sections.

在“按钮”单击上,我们显示在前面的部分中定义的特定Toast。

The output of the above application in action is given below.

下面给出了上面应用程序的输出。

AndroidlyToasts

AndroidlyToasts

翻译自: https://www.journaldev.com/96/android-toast-kotlin

使用Kotlin的Android Toast相关推荐

  1. Kotlin on Android 开发环境介绍

    Kotlin 被 Google 采纳为 Android 开发一级编程语言,到现在也一年多了,我们团队从去年 10 月份开始部分项目尝试用 Kotlin 开发,到现在决定推广到全部项目,因为一旦用上 K ...

  2. 使用Kotlin开发Android应用初体验

    使用Kotlin开发Android应用初体验 昨晚,最近一届的谷歌IO大会正式将Kotlin确定为了官方开发语言,作为一名Android开发鸟,怎么能不及时尝尝鲜呢? Kotlin的简要介绍 在开发之 ...

  3. 【翻译】ANDROID KTX – 使用Kotlin进行Android开发

    原文地址:ANDROID KTX – ANDROID DEVELOPMENT WITH KOTLIN [正在翻译中] 介绍 Android KTX is an open source library ...

  4. 出现身份验证错误 要求的函数不受支持_学习使用Kotlin创建Android应用程序第3部分:身份验证登录...

    在上一篇文章中,我们讨论了学习Kotlin制作Android应用程序的初学者第2部分:创建登录表单.这次我们来学习创建登录表单后,我们将尝试对上一篇创建的登录表单使用Firebase身份验证.因此,我 ...

  5. 使用Kotlin的Android ListView

    In this tutorial, we'll implement ListView in our Android apps using Kotlin. 在本教程中,我们将使用Kotlin在Andro ...

  6. 使用Kotlin的Android Spinner

    In this tutorial, we'll be discussing and implementing Spinners in our Android Application using Kot ...

  7. 使用Kotlin的Android ToggleButton

    In this tutorial, we'll learn how to implement Android ToggleButton using Kotlin. We will learn how ...

  8. kotlin写android,Kotlin安卓开发

    1.配置Android Studio a.在Project对应的build.gradle文件中添加如下代码: buildscript { ext.kotlin_version ='1.2.30' // ...

  9. 用 Kotlin 开发 Android 项目是一种什么样的感受?(二)

    前言 前面我已经写了一篇名为<用 Kotlin 开发 Android 项目是一种什么样的感受?>的文章.文中多数提到的还是 Kotlin 语言本身的特点,而 Kotlin 对于 Andro ...

最新文章

  1. 5月17日 AJAX 之 XML
  2. Git科普文,Git基本原理各种骚操作
  3. 前端 网络安全 前端优化 代码架构 笔记
  4. linux安装编译cmake,centos7下编译安装cmake-3.13.2
  5. GridView页脚汇总(统计)行的方法(.net 2.0)
  6. Android权限全记录(转)
  7. 【遥感图像处理软件】ArcGIS Pro 使用总结
  8. 自动化测试环境搭建--Python及selenium
  9. 啦啦外卖41.7亲测可用!插件齐全!含顾客APP,商家APP ,骑手APP!需要的拿去研究
  10. 去阿诗玛的故乡 云南昆明自助攻略
  11. 西方文化系列讲座之罗马、基督教文化
  12. Echart自定义图片绘制热力图实现图片适配
  13. 315来了,跨境卖家们赶紧自检容易被维权举报的问题
  14. 2022.04.10-高宝琪毕设阶段性汇报
  15. JS编写 三角形三边求面积
  16. 前端学习——HTML(二) 列表
  17. Your PHP version does not satisfy that requirement
  18. Javascript(JS) leetcode 804. 唯一摩尔斯密码词
  19. 分享127个ASP源码,总有一款适合您
  20. 没有“光线追踪”,赛博朋克2077就算残废?

热门文章

  1. 2-9 prev + next选择器 “远亲不如近邻” 返回且只返回唯一-个元素。 而通过prev + next选择器就可以查找与“prev”元素紧邻的下一个“next”元素...
  2. PHP学习笔记(八)
  3. 笔记(2015.8.1)
  4. 缓存jQuery对象来提高性能
  5. 数据库设计经验浅谈(3,4,5)转载
  6. [转载] Python字典的setdefault()方法
  7. [转载] 树莓派并行控制电机_使用由并行端口控制的软盘驱动步进电机的相机摇摄器
  8. [转载] python——连接Oracle数据库
  9. SDR与DDR的区别
  10. E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/t