I have a button and on button click toast appears, if the user clicks on button several times and go to previous activity or even close the aplication toast is still visible,
How to finish or cancel the toast when user goes to any other activity or how to prevent generation of toast?
Toast.makeText(getApplicationContext(), "Enter correct goal!",
Toast.LENGTH_SHORT).show()
try this cancel() Toast by using handler
Toast toast = Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 500);
You can cancel individual Toasts by calling cancel() on the Toast object. AFAIK, there is no way for you to cancel all outstanding Toasts, though.
When calling finish() on an activity, the method onDestroy() is executed this method can do things like:
Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed.
So make object of Toast in your class and call cancel() in onDestroy() method
Class YourClassActivity extends Activity{
private static Toast toast;
public void initToast(){
if (toast != null)
toast.cancel();
toast = Toast.makeText(MainActivity.this,"text",Toast.LENGTH_SHORT);
toast.setText("Enter correct goal!");
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void onDestroy() {
super.onDestroy();
if (toast != null)
toast.cancel();
}
@Override
protected void onStop(){
super.onStop();
if (toast != null)
toast.cancel();
}
}
Call initToast() method inside your Button click event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With