Using Madur's excellent answer above, I extended this into a class that would deal with different types of messages:
public class ToastManager {
private Toast toastWarningMessage;
private Toast toastAddMessage;
...
public void messageWarning(Context context, String message) {
if(toastWarningMessage == null) {
toastWarningMessage = Toast.makeText(context, message, Toast.LENGTH_SHORT);
} else {
toastWarningMessage.cancel();
toastWarningMessage.setText(message);
}
toastWarningMessage.show();
}
public void messageAdd(Context context, String message) {
if(toastAddMessage == null) {
toastAddMessage = Toast.makeText(context, message, Toast.LENGTH_SHORT);
} else {
toastAddMessage.cancel();
toastAddMessage.setText(message);
}
toastAddMessage.show();
}
...
}
And this is called from within my main activity:
ToastManager toastManager;
...
private void toastWarningMessage(String message) {
if(toastManager == null) toastManager = new ToastManager();
toastManager.messageWarning(this, message);
}
The reason for classifying the messages is to make sure that no important messages are overwritten. This solution seems easy to reuse as it only involves renaming the Toasts and the function names.
When the user spams the button, the toast will just cancel each time for the same message type. The only problem is if the user can spam a mix of messages. This leads to the first message repeating and once it finally expires the other messages showing once each. Not really a huge problem, but something to be aware of.
I haven't looked into possible downsides of having multiple Toast instances.