35

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

问题是,吐司需要时间来显示,当我滚动它的速度足够快时,例如,我滚动到“2012/05”和“2012/06”并且没有暂停滚动到“2012/07”,我必须等待“2012/05”、“2012/06”、“2012/07”的Toast将一一呈现。

似乎Android有一个看不见的队列来管理toast

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

我搜索了“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();
4

12 回答 12

24

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

Toast toastMessage;

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

if (toastMessage!= null) {
    toastMessage.cancel();
}
toastMessage= Toast.makeText(context, "The message you want to display", duration);
toastMessage.show();
于 2015-08-10T14:12:31.877 回答
23

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

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


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

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

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

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

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


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

}
于 2013-04-19T11:25:04.673 回答
17

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

toastObject.cancel()
于 2012-04-09T08:28:10.417 回答
7

这是代码。

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

现在可以使用 toastobject 的 Object。其参考

toastobject.cancel();

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

于 2012-04-09T07:24:21.227 回答
6

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

myToast.setText(toastMsg);
myToast.show();
于 2014-12-19T16:09:58.440 回答
3

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

private Toast toast;

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

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

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

showToast("message 1");

//一段时间后

showToast("message 2");

希望能帮助到你。

于 2018-06-25T09:25:46.277 回答
1

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

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

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

于 2012-04-09T07:24:41.333 回答
1

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

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();
}
于 2015-06-27T16:11:41.463 回答
1

简单的。一旦你想创建另一个 toast,只需在 toast 上调用方法 .cancel() 即可。

首先像这样在类的顶部定义一个 Toast 变量

private Toast mToast;

稍后,当您想创建一个新的 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. 
于 2017-05-29T07:56:31.287 回答
0
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();

    }

}
于 2015-10-09T07:45:46.500 回答
0

迟来的:您的代码不起作用的原因是它Toast.makeText()没有返回Toast对它正在创建的引用。它只是一个帮助方法,旨在允许Toast快速轻松地创建,但不允许引用或取消。要取消,您必须执行以下操作:

t=Toast(requireContext())
t.setText(YOUR TEXT)
t.setDuration(1000)
t.show()

这样 t 将在调用构造函数时被分配一个引用,这将允许稍后取消。

于 2021-11-11T04:15:12.640 回答
-1

您可以使用一种拍摄技术。好的,让我们开始定义:

private Toast mToast;
private showOnce=false;

稍后当你想展示一次吐司时:

if(showOnce==false){
  mToast=Toast.makeText(this, "Once!", Toast.LENGTH_LONG);
  mToast.show();
  showOnce=true;
}
于 2017-08-27T18:03:19.377 回答