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.
吐司需要三个参数。
- Context 语境
- Message 信息
- 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 la