Android 当我想展示另一个 Toast 时,我可以取消之前的 Toast 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10070108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:22:35  来源:igfitidea点击:

Can I cancel previous Toast when I want to show an other Toast?

androidtoast

提问by topxebec

In my app, I construct a calendar widget for my activity, when I scroll it to previous or next month, I let it make a toast and show it.

在我的应用程序中,我为我的活动构建了一个日历小部件,当我将它滚动到上个月或下个月时,我让它敬酒并显示它。

The question is, the toast need time to show, when I scroll it fast enough, for example, I scrolled to "2012/05" and "2012/06" and scroll to "2012/07" without pause, I have to wait the Toast of "2012/05", "2012/06","2012/07" to show one by one slowly.

问题是,吐司需要时间来显示,当我滚动它的速度足够快时,例如我滚动到“2012/05”和“2012/06”并没有停顿地滚动到“2012/07”,我必须等待“2012/05”、“2012/06”、“2012/07”的祝酒词一一慢慢展现。

Seems like Android has an invisible queue to manage toasts

好像Android有一个看不见的队列来管理toasts

how can I clean it and only show the last toast? Can I show a specific Toast immediately without waiting?

我怎样才能清洁它并只显示最后的吐司?我可以立即显示特定的 Toast 而无需等待吗?

I searched the "android.widget.Toast.java"and find a method cancel(), but unfortunately it does not work as follows.

我搜索了“android.widget.Toast.java”并找到了一个方法cancel(),但不幸的是它不起作用如下。

if (t != null) {
    t.cancel();
}
t = Toast.makeText(this.mContext, mHelper.getYear() + "年"
                + (mHelper.getMonth() + 1) + "月", Toast.LENGTH_SHORT);
t.show();

采纳答案by Mohammed Azharuddin Shaikh

You need to call method on correct object.

您需要在正确的对象上调用方法。

toastObject.cancel()

回答by Richard Le Mesurier

Here is my answer copied from another similar question here:

这是我从另一个类似问题复制过来的答案:

The Boastclass accomplishes exactly what you need. Most recent code can be found on GitHub here:

Boast课程完全满足您的需求。最新的代码可以在 GitHub 上找到:



The trick is to keep track of the last Toastthat was shown, and to cancel that one.

诀窍是跟踪显示的最后一个Toast,并取消那个。

What I have done is to create a Toastwrapper, that contains a static reference to the last Toast displayed.

我所做的是创建一个Toast包装器,其中包含对最后显示的 Toast 的静态引用。

When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).

当我需要显示一个新的时,我首先取消静态引用,然后再显示新的(并将其保存在静态中)。

Here's full code of the Boastwrapper I made - it mimics enough of the Toast methods for me to use it. By default the Boastwill cancel the previous one, so you don't build up a queue of Toasts waiting to be displayed.

这是Boast我制作的包装器的完整代码- 它模仿了足够多的 Toast 方法供我使用。默认情况下,Boast将取消前一个,因此您不会建立等待显示的 Toast 队列。

If you just want to know how to cancel the notifications when exiting your app, you will find lots of help in there.

如果您只想知道如何在退出应用程序时取消通知,您会在那里找到很多帮助。



package mobi.glowworm.lib.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.widget.Toast;

import java.lang.ref.WeakReference;

/**
 * {@link Toast} decorator allowing for easy cancellation of notifications. Use this class if you
 * want subsequent Toast notifications to overwrite current ones. </p>
 * <p/>
 * By default, a current {@link Boast} notification will be cancelled by a subsequent notification.
 * This default behaviour can be changed by calling certain methods like {@link #show(boolean)}.
 */
public class Boast {
    /**
     * Keeps track of certain Boast notifications that may need to be cancelled. This functionality
     * is only offered by some of the methods in this class.
     * <p>
     * Uses a {@link WeakReference} to avoid leaking the activity context used to show the original {@link Toast}.
     */
    @Nullable
    private volatile static WeakReference<Boast> weakBoast = null;

    @Nullable
    private static Boast getGlobalBoast() {
        if (weakBoast == null) {
            return null;
        }

        return weakBoast.get();
    }

    private static void setGlobalBoast(@Nullable Boast globalBoast) {
        Boast.weakBoast = new WeakReference<>(globalBoast);
    }


    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Internal reference to the {@link Toast} object that will be displayed.
     */
    private Toast internalToast;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Private constructor creates a new {@link Boast} from a given {@link Toast}.
     *
     * @throws NullPointerException if the parameter is <code>null</code>.
     */
    private Boast(Toast toast) {
        // null check
        if (toast == null) {
            throw new NullPointerException("Boast.Boast(Toast) requires a non-null parameter.");
        }

        internalToast = toast;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Make a standard {@link Boast} that just contains a text view.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param text     The text to show. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text, int duration) {
        return new Boast(Toast.makeText(context, text, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the text from a resource.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param resId    The resource id of the string resource to use. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException {
        return new Boast(Toast.makeText(context, resId, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view. Duration defaults to
     * {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param text    The text to show. Can be formatted text.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text) {
        return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the text from a resource.
     * Duration defaults to {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param resId   The resource id of the string resource to use. Can be formatted text.
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId) throws Resources.NotFoundException {
        return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Show a standard {@link Boast} that just contains a text view.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param text     The text to show. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     */
    public static void showText(Context context, CharSequence text, int duration) {
        Boast.makeText(context, text, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the text from a resource.
     *
     * @param context  The context to use. Usually your {@link android.app.Application} or
     *                 {@link android.app.Activity} object.
     * @param resId    The resource id of the string resource to use. Can be formatted text.
     * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or
     *                 {@link Toast#LENGTH_LONG}
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    public static void showText(Context context, int resId, int duration)
            throws Resources.NotFoundException {
        Boast.makeText(context, resId, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view. Duration defaults to
     * {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param text    The text to show. Can be formatted text.
     */
    public static void showText(Context context, CharSequence text) {
        Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the text from a resource.
     * Duration defaults to {@link Toast#LENGTH_SHORT}.
     *
     * @param context The context to use. Usually your {@link android.app.Application} or
     *                {@link android.app.Activity} object.
     * @param resId   The resource id of the string resource to use. Can be formatted text.
     * @throws Resources.NotFoundException if the resource can't be found.
     */
    public static void showText(Context context, int resId) throws Resources.NotFoundException {
        Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally
     * have to call this. Normally view will disappear on its own after the appropriate duration.
     */
    public void cancel() {
        internalToast.cancel();
    }

    /**
     * Show the view for the specified duration. By default, this method cancels any current
     * notification to immediately display the new one. For conventional {@link Toast#show()}
     * queueing behaviour, use method {@link #show(boolean)}.
     *
     * @see #show(boolean)
     */
    public void show() {
        show(true);
    }

    /**
     * Show the view for the specified duration. This method can be used to cancel the current
     * notification, or to queue up notifications.
     *
     * @param cancelCurrent <code>true</code> to cancel any current notification and replace it with this new
     *                      one
     * @see #show()
     */
    public void show(boolean cancelCurrent) {
        // cancel current
        if (cancelCurrent) {
            final Boast cachedGlobalBoast = getGlobalBoast();
            if ((cachedGlobalBoast != null)) {
                cachedGlobalBoast.cancel();
            }
        }

        // save an instance of this current notification
        setGlobalBoast(this);

        internalToast.show();
    }

}

回答by JCarangoH

You just need to declare a "Toast" var like this:

你只需要像这样声明一个“Toast”变量:

Toast toastMessage;

Then in your function, do it like this:

然后在你的函数中,这样做:

if (toastMessage!= null) {
    toastMessage.cancel();
}
toastMessage= Toast.makeText(context, "The message you want to display", duration);
toastMessage.show();

回答by user3533716

You can reuse a toast, this will make it display immediately.

您可以重复使用 Toast,这将使其立即显示。

myToast.setText(toastMsg);
myToast.show();

回答by Bhavin

Here is the Code.

这是代码。

final Toast toastobject = Toast.makeText(context, "This message will disappear when toast.close(); is called", Toast.LENGTH_SHORT);

Now you can use the Object of toastobject. Its Reference

现在你可以使用 toastobject 的对象了。其参考

toastobject.cancel();

You can use it in Thread or whenever you would like to Close the Toast.

您可以在 Thread 中使用它,也可以在您想要关闭 Toast 时使用它。

回答by Gaurang Goda

There are many ways by which we can cancel previous Toast when we want to show another Toast. below I have written a simplest an easy way to implement it. First of all, we have to create a variable which can be accessed in the whole class.

当我们想显示另一个 Toast 时,我们可以通过多种方式取消之前的 Toast。下面我写了一个最简单的方法来实现它。首先,我们必须创建一个可以在整个类中访问的变量。

private Toast toast;

After creating the variable which can be accessed by whole class we have to create a method in our class which displays the toast message and checks if the previous toast is displaying then cancel it.

创建可以被整个类访问的变量后,我们必须在我们的类中创建一个方法,该方法显示 toast 消息并检查前一个 toast 是否正在显示然后取消它。

   public void showToast(String message) {
    if (toast != null) {
        toast.cancel();
    }
    toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
    toast.show();
}

you can change toast message by runtime calling above method.

您可以通过运行时调用上述方法来更改吐司消息。

showToast("message 1");

//after some time

//一段时间后

showToast("message 2");

hope it helps.

希望能帮助到你。

回答by JonA

Toast has a method to hide current toast message

Toast 有一种隐藏当前 Toast 消息的方法

public void cancel() {
    mTN.hide();
}

Try calling t.cancel() when it is necessary.

必要时尝试调用 t.cancel() 。

回答by tun

You can create static method and use it to show a toast:

您可以创建静态方法并使用它来显示祝酒词:

public static Toast toast = null;
public static showToast(Context context,String msg){
if(toast!=null)             //this will cancel the toast on the screen if one exists
   toast.cancel();
toast = Toast.makeText(context,msg);
toast.show();
}

回答by Sreehari R

Simple. Simply call the method .cancel() on the toast once you want to create another toast.

简单的。一旦您想创建另一个吐司,只需在吐司上调用 .cancel() 方法。

Start by defining a Toast variable at the top of your class like this

首先在类的顶部定义一个 Toast 变量,如下所示

private Toast mToast;

Later, When you want to create a new Toast(and have the old one disappear), do this.

稍后,当您想创建一个新的 Toast(并让旧的 Toast 消失)时,请执行此操作。

if(mToast != null) {
  mToast.cancel();  //if a toast exists it deletes it, allowing you to create a new one
}


mToast = Toast.makeText(this, "This will show up now!", Toast.LENGTH_LONG);
mToast.show(); //creates the new toast. 

回答by hamsayogam

public static Toast  sToast=null;

// create Toast object;

public void showToast(String msg)

    {

    //here is checking whether toast object is null or not;if not null gonna cancel the toast that is showing in phone window and make it null;  

    if(sToast!=null)
    {

      sToast.cancel;

    sToast=null;
    }

    //if toast object is null,gonna create new instance and make it shown on phone window.

    if(sToast==null)
    {

        sToast=Toast.makeText(currentActivity.this,msg,Duration);

        sToast.setGravity();

        sToast.show();

    }

}