杀死Android吐司?

时间:2015-01-20 10:19:01

标签: android toast android-toast

我有一个按钮并且按钮点击吐司出现,如果用户多次点击按钮并转到上一个活动甚至关闭应用程序吐司仍然可见,

当用户参加任何其他活动或如何防止吐司生成时,如何完成或取消祝酒?

Toast.makeText(getApplicationContext(), "Enter correct goal!",
                        Toast.LENGTH_SHORT).show()

3 个答案:

答案 0 :(得分:3)

使用cancel()

尝试此Toast 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);

答案 1 :(得分:0)

您可以通过调用Toasts对象上的cancel()来取消个人Toast。 AFAIK,你无法取消所有未完成的Toasts

在活动上调用完成()时,会执行 onDestroy()方法,此方法可以执行以下操作:

  1. 关闭活动管理的所有对话框。
  2. 关闭活动管理的所有游标。
  3. 关闭所有打开的搜索对话框
  4. 此外, onDestroy()不是析构函数。它实际上并没有破坏对象。它只是一种基于某种状态调用的方法。因此,在超类的onDestroy()运行并返回之后,你的实例仍然存活并且非常好*。如果用户想要重新启动应用程序,Android会保持进程,这会使启动阶段更快。该过程将不会执行任何操作,如果需要回收内存,则该过程将被终止。

    因此,请在班级中设置Toast的对象,并在cancel()方法中调用onDestroy()

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

    initToast()点击事件中调用Button方法。

答案 2 :(得分:0)

Toastunrelated to their context

你可以使用替代方案(AppMsg,Crouton或新的SnackBar),或者在你的Toast中保留对cancel()Activity.onPause()的引用。