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。
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消息用于向用户显示不重要的内容,但可能会帮助用户了解应用程序中当前发生的情况。 例如,为表单中的特定字段提供提示。
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.
吐司需要三个参数。
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.
我们可以自定义吐司的布局及其持续时间。
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文件的布局。
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消息。
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()
等效。
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)
To create a Custom Toast programmatically we use a custom layout.
要以编程方式创建“自定义吐司”,我们使用自定义布局。
Following is the custom layout defined:
以下是定义的自定义布局:
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 = message
layout.imageView.setBackgroundResource(imageSrc)
setGravity(Gravity.CENTER, 0, 0)
duration = Toast.LENGTH_SHORT
view = layout
show()
}
}
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触发到屏幕上。
The code for the MainActivity.kt Kotlin’s class is given below.
下面给出了MainActivity.kt Kotlin类的代码。
package net.androidly.androidlytoasts
import 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 = message
layout.imageView.setBackgroundResource(imageSrc)
setGravity(Gravity.CENTER, 0, 0)
duration = Toast.LENGTH_SHORT
view = layout
show()
}
}
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