Reputation: 171
Trying to display multiple Toast messages one after another, but only the last toast message gets displayed. I tried using Thread.sleep, and handlers to buffer the messages, but neither worked. Any other tips? Here's my code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_cow)
// updates the variables with these values
Submit.setOnClickListener {
cowName = Cow_Name.text.toString()
cowWeight = Cow_Weight.text.toString().toIntOrNull()
cowSex = Cow_Sex.text.toString()
cowAge = Cow_Age.text.toString()
showToast(cowName.toString())
showToast(cowWeight.toString())
showToast(cowSex.toString())
showToast(cowAge.toString())
}
}
private fun showToast(text: String)
{
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
handler.postDelayed ({
// Do nothing
}, 2000)
}
Upvotes: 0
Views: 1345
Reputation: 2958
At minimum you should add a "delay" variable to "showToast" and move the Toast
call to inside the posted Runnable
:
private fun showToast(text: String, delayInMilliseconds: Int) {
val context = this
handler.postDelayed (
{ Toast.makeText(context, text, Toast.LENGTH_SHORT).show() },
delayInMilliseconds
)
}
Then you'd call it like
showToast(cowName.toString(), 0)
showToast(cowWeight.toString(), 1000)
showToast(cowSex.toString(), 2000)
showToast(cowAge.toString(), 3000)
Or whatever delay values were required to make that work.
Upvotes: 3