In Kotlin I use this:
private lateinit var toast: Toast
fun showToast(@StringRes stringId: Int, toastLength: Int = Toast.LENGTH_SHORT)
{
if (this::toast.isInitialized)
{
toast.cancel()
}
toast = Toast.makeText(
requireContext(),
getString(stringId),
toastLength
)
toast.show()
}
Or when using it in many fragments it is possible to extend the Fragment
class, so function showToast
doesn't have to be in every fragment.
open class OneToastFragment : Fragment()
{
private lateinit var toast: Toast
fun showToast(@StringRes stringId: Int, toastLength: Int = Toast.LENGTH_SHORT)
{
if (this::toast.isInitialized)
{
toast.cancel()
}
toast = Toast.makeText(
requireContext(),
getString(stringId),
toastLength
)
toast.show()
}
}
Also, it can be easy using Toasty library.
Gradle project:
repositories {
...
maven { url "https://jitpack.io" }
}
Gradle module app:
dependencies {
...
implementation 'com.github.GrenderG:Toasty:1.4.2'
}
onCreate in Activity class:
Toasty.Config.getInstance().allowQueue(false).apply(); // set this to avoid toast acumulations
//Test:
int x = 0;
Toasty.info(this, Integer.toString(x++), Toast.LENGTH_SHORT, true).show();
Toasty.info(this, Integer.toString(x++), Toast.LENGTH_SHORT, true).show();
Toasty.info(this, Integer.toString(x++), Toast.LENGTH_SHORT, true).show();
//This will only show a toast with message `2`