Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill android toast?

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()
like image 740
PK__ Avatar asked May 27 '26 08:05

PK__


2 Answers

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);
like image 158
M D Avatar answered May 31 '26 12:05

M D


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:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog

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.

like image 41
Himanshu Agarwal Avatar answered May 31 '26 13:05

Himanshu Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!