[英]How do you display a Toast using Kotlin on Android?
In different Kotlin examples for Android I see toast("Some message...")
or toastLong("Some long message")
.在 Android 的不同 Kotlin 示例中,我看到
toast("Some message...")
或toastLong("Some long message")
。 For example:例如:
view.setOnClickListener { toast("Click") }
As I understand, it is an Extension Function for Activity
.据我了解,它是
Activity
的扩展功能。
How and where do you define this toast()
function so that you are able to use it throughout the project?您如何以及在何处定义此
toast()
函数,以便您能够在整个项目中使用它?
It can be an extension function for Context
:它可以是
Context
的扩展函数:
fun Context.toast(message: CharSequence) =
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
You can place this anywhere in your project, where exactly is up to you.您可以将其放置在项目中的任何位置,具体位置由您决定。 For example, you can define a file
mypackage.util.ContextExtensions.kt
and put it there as a top level function.例如,您可以定义一个文件
mypackage.util.ContextExtensions.kt
并将其作为顶级函数放在那里。
Whenever you have access to a Context
instance, you can import this function and use it:只要您有权访问
Context
实例,就可以导入此函数并使用它:
import mypackage.util.ContextExtensions.toast
fun myFun(context: Context) {
context.toast("Hello world!")
}
这是 Kotlin 中的一行解决方案:
Toast.makeText(this@MainActivity, "Its toast!", Toast.LENGTH_SHORT).show()
It's actually a part of Anko , an extension for Kotlin.它实际上是Anko的一部分,是 Kotlin 的扩展。 Syntax is as follows:
语法如下:
toast("Hi there!")
toast(R.string.message)
longToast("Wow, such a duration")
In your app-level build.gradle
, add implementation "org.jetbrains.anko:anko-common:0.8.3"
在您的应用程序级
build.gradle
,添加implementation "org.jetbrains.anko:anko-common:0.8.3"
Add import org.jetbrains.anko.toast
to your Activity.将
import org.jetbrains.anko.toast
添加到您的活动中。
Try this试试这个
In Activity活动中
Toast.makeText(applicationContext, "Test", Toast.LENGTH_LONG).show()
or或
Toast.makeText(this@MainActiivty, "Test", Toast.LENGTH_LONG).show()
In Fragment在片段中
Toast.makeText(activity, "Test", Toast.LENGTH_LONG).show()
or或
Toast.makeText(activity?.applicationContext, "Test", Toast.LENGTH_LONG).show()
If you don't want to use anko
and want to create your own Toast
extension.如果您不想使用
anko
并想创建自己的Toast
扩展。 You can create inline(or without inline) extensions defined in a kotlin file(with no class) and with that you can access this function in any class.您可以创建在 kotlin 文件(没有类)中定义的内联(或不内联)扩展,并且您可以在任何类中访问此函数。
inline fun Context.toast(message:String){
Toast.makeText(this, message , duration).show()
}
Usage:用法:
In Activity,在活动中,
toast("Toast Message")
In Fragment,在片段中,
context?.toast("Toast Message")
While using Anko with Kotlin , inside fragment use either:在Kotlin 中使用Anko时,在片段内部使用:
activity.toast("string message")
or或
context.toast("string message")
or或
view.holder.context.toast("string message")
A very simple extension.一个非常简单的扩展。
Add this to a toast.kt file将此添加到 toast.kt 文件中
import android.content.Context
import android.widget.Toast
import androidx.fragment.app.Fragment
inline fun Context.toast(message:()->String){
Toast.makeText(this, message() , Toast.LENGTH_LONG).show()
}
inline fun Fragment.toast(message:()->String){
Toast.makeText(this.context, message() , Toast.LENGTH_LONG).show()
}
then you'll have那么你会有
toast {
"Hello World"
}
in both fragment & activity.在片段和活动中。
I have found very easy way to Toast from given link https://gist.github.com/felipearimateia/ee651e2694c21de2c812063980b89ca3 .我从给定的链接https://gist.github.com/felipearimateia/ee651e2694c21de2c812063980b89ca3找到了非常简单的 Toast 方法。 In this link Activity is used instead of Context.
在此链接中,使用 Activity 而不是 Context。 Try it.
试试吧。
With this extension function for Toasts , you can call them in Activities as well as Fragments, you can pass this as Context
for Activities or getApplication()
for Fragments, also it's generated with Toast.LENGTH_SHORT
as default, so you don't need to worry to pass it as a parameter, but you can overwrite it as well if you need.使用Toasts 的这个扩展函数,您可以在活动和片段中调用它们,您可以将其作为活动的
Context
或getApplication()
传递给片段,它也是使用Toast.LENGTH_SHORT
作为默认生成的,因此您不需要担心将其作为参数传递,但如果需要,您也可以覆盖它。
fun Context.showToast(message: String, duration: Int = Toast.LENGTH_SHORT){
Toast.makeText(context, message , duration).show()
}
showToast("John Doe")
if you want to override the duration.如果你想覆盖持续时间。
showToast("John Doe", Toast.LENGTH_LONG)
Show a Toast not from the UI Thread , in a Fragment在片段中显示不是来自 UI 线程的 Toast
activity?.runOnUiThread {
Toast.makeText(context, "Image saved to the Gallery", Toast.LENGTH_SHORT).show()
}
Android Toast for Kotlin适用于 Kotlin 的 Android Toast
Activity
活动
Toast.makeText(applicationContext, "message...", Toast.LENGTH_SHORT).show()
Fragment
片段
Toast.makeText(activity, "message...", Toast.LENGTH_SHORT).show()
Just to add on @nhaarman's answer --> you probably want to add the resourceId
support as well只是添加@nhaarman 的答案--> 您可能还想添加
resourceId
支持
fun Context.toast(resourceId: Int) = toast(getString(resourceId))
fun Context.toast(message: CharSequence) =
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
Download source code from here ( Custom Toast In Android Kotlin )从这里下载源代码( Android Kotlin 中的自定义 Toast )
fun Toast.createToast(context: Context, message: String, gravity: Int, duration: Int, backgroucolor: String, imagebackgroud: Int) {
val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
/*first parameter is the layout you made
second parameter is the root view in that xml
*/
val layout = inflater.inflate(R.layout.custom_toast, (context as Activity).findViewById(R.id.custom_toast_container))
layout.findViewById(R.id.tv_message).text = message
layout.setBackgroundColor(Color.parseColor(backgroucolor))
layout.findViewById(R.id.iv_image).iv_image.setImageResource(imagebackgroud)
setGravity(gravity, 0, 100)
setDuration(Toast.LENGTH_LONG);
setView(layout);
show()
}
Thanks!谢谢!
the way I use it simply creating an Object
/ Class
我使用它的方式只是创建一个
Object
/ Class
object UtilKotlin {
fun showMessage(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
and calling the method并调用方法
UtilKotlin.showMessage(activity, "Sets 0 !") // in activity trying this
Custom Toast with Background color Text size AND NO XML file inflated Try the code without setting the Background color带有背景颜色的自定义 Toast 文本大小且没有膨胀的XML文件尝试不设置背景颜色的代码
fun theTOAST(){
val toast = Toast.makeText(this@MainActivity, "Use View Person List",Toast.LENGTH_LONG)
val view = toast.view
view.setBackgroundColor(Color.TRANSPARENT)
val text = view.findViewById(android.R.id.message) as TextView
text.setTextColor(Color.BLUE)
text.textSize = (18F)
toast.show()
}
Here is extension of toast for activity or fragment这是活动或片段的吐司扩展
fun showToast(context: Context,@StringRes string : Int, duration: Int = Toast.LENGTH_SHORT){
Toast.makeText(context,string,duration).show()
}
inline fun Context.toast(message:()->String){
Toast.makeText(this, message() , Toast.LENGTH_LONG).show()
}
inline fun Fragment.toast(message: () -> String, duration: () -> Int = { Toast.LENGTH_LONG }){
Toast.makeText(this.context,message(),duration()).show()
}
inline fun AppCompatActivity.toast(message: () -> String, duration: () -> Int = { Toast.LENGTH_LONG }){
Toast.makeText(this.applicationContext,message(),duration()).show()
}
If you want simple toast just call first method both fragment and activity如果你想要简单的吐司,只需调用第一个方法片段和活动
showToast(yourContext,"your message") or showToast(yourContext,"your message",1200L)
Or或者
toast {
"Your message"
}
Or或者
toast({"your message"}) or toast({"your messge"},{your duration = 1200L})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.