I have a simple app with a button and click listener on it which displays a toast with the number of clicks that have been performed on the button:
class MainActivity : AppCompatActivity() {
private val toast by lazy { Toast.makeText(this, "", LENGTH_LONG) }
var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener { updateToast() }
}
private fun updateToast() {
count++
toast.setText(count.toString())
toast.show()
}
}
The problem I have is that the duration of the toast is not renewed after each click and after 20 clicks (for example) the toast disappears and never shows again, even if I set its duration again before showing:
private fun updateToast() {
count++
toast.setText(count.toString())
toast.duration = LENGTH_LONG
toast.show()
}
I can always cancel the currently displayed toast and create new one, but I wanna know if there is a way to update the text on the existing toast and tell it to stay on the screen for the duration of a newly created toast.
Even if there is, don't do that.
From a user experience point of view, imagine if a Toast
pops up and says Your file was saved
, and then it suddenly changes to Your file wasn't saved
.
Without a well-defined graphical transaction between the two messages, the user is very likely to miss the text update.
That's why the Toast
is supposed to be an immutable
element.
If you need to communicate something new, use a different Toast
.
And this is actually a problem in some Android
devices: two subsequent Toast
messages often do not fade-out
and fade-in
accentuatedly enough; and if the text length if quite similar between the two messages, you'll probably not notice the latter.