页面变化时不显示Toast消息

问题描述 投票:0回答:2

我正在创建一条 Toast 消息。当您输入错误的信息时,会出现此 toast,但是当我快速键入并再次输入正确的数据时,toast 消息继续出现在新页面上。

我不想写 LENGTH_SHORT,因为该人需要能够轻松阅读消息

我为此编写了一个扩展,但它对我不起作用

private fun Context.toastCreate(): Toast {
    return Toast(this)
}

fun Context.showError(message: String) {
    val inflater = LayoutInflater.from(this)
    val layout: View = inflater.inflate(R.layout.custom_toast_layout, null)
    val text = layout.findViewById<TextView>(R.id.text)
    text.text = message
    val toast = toastCreate()
    toast.duration = Toast.LENGTH_LONG
    toast.view = layout
    toast.show()
}

fun Context.cancelError() {
    this.toastCreate().cancel()
}
android kotlin android-toast
2个回答
0
投票

您似乎想在用户快速更正输入时阻止 toast 消息显示在新页面上。您面临的问题是因为页面更改时未取消 toast 消息。每次调用 toastCreate() 函数都会创建一个新的 Toast 实例,因此 cancelError() 不会取消之前的 toast。

要解决此问题,您应该维护对当前 Toast 实例的引用,并在显示新的 toast 消息之前取消它。这是实现此目的的代码的更新版本:

private var currentToast: Toast? = null

fun Context.showError(message: String) {
    // Cancel the current toast if it exists
    currentToast?.cancel()

    val inflater = LayoutInflater.from(this)
    val layout: View = inflater.inflate(R.layout.custom_toast_layout, null)
    val text = layout.findViewById<TextView>(R.id.text)
    text.text = message

    // Create a new toast and set it as the current toast
    currentToast = Toast(this)
    currentToast?.duration = Toast.LENGTH_LONG
    currentToast?.view = layout
    currentToast?.show()
}

fun Context.cancelError() {
    // Cancel the current toast if it exists
    currentToast?.cancel()
}

0
投票

我认为您当前的方法不起作用,因为您的

Context.toastCreate()
总是返回一个新的 Toast 实例。因此,在 cancelError() 函数中,您创建了一个新的 Toast 并立即取消它。但这不会影响当前显示的Toast。
要取消 Toast,您需要在当前显示的 Toast 实例上调用
cancel()
函数。

您可以将最后创建的 toast 存储在变量中:

private var currentToast: Toast? = null
private fun Context.toastCreate(): Toast {
    var newToast = Toast(this)
    currentToast = newToast
    return newToast
}

然后在启动新的 Activity 时调用此 Toast 实例的取消方法:

startActivity(...)
currentToast?.cancel()

有关带有扩展功能的 Toast 功能的完整实现,请参阅 这个 StackOverflow 答案

© www.soinside.com 2019 - 2024. All rights reserved.