Don't show toast message when the page changes

I'm creating a Toast message. When you type the information incorrectly, this toast appears, but when I quickly type and enter the correct data again, the toast message continues to appear on the new page.

I don't want to write LENGTH_SHORT because the man needs to be able to read the message easily

I wrote an extensions for this but it didn't work for me

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()
}

Upvotes: 1

Views: 214

Answers (1)

BenjyTec
BenjyTec

Reputation: 10942

I think your current approach is not working because your Context.toastCreate() always returns a new Toast instance. So in your cancelError() function, you create a new Toast and immediately cancel it. But this does not effect the currently shown Toast.
To cancel a Toast, you need to call the cancel() function on the Toast instance that is currently displayed.

You can store the last created toast in a variable:

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

Then call the cancel method on this Toast instance when you start the new Activity:

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

For a complete implementation of Toast functionality with extension functions, refer to this StackOverflow answer.

Upvotes: 1

Related Questions