Kill android toast?

限于喜欢 提交于 2019-12-11 11:28:40

问题


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()

回答1:


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);



回答2:


Toasts are unrelated to their context.

You can use an alternative (AppMsg, Crouton or the new SnackBar), or keep a reference to your Toast and cancel() it in your Activity.onPause() let's say.




回答3:


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.



来源:https://stackoverflow.com/questions/28042825/kill-android-toast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!