当我想要展示其他Toast时,我可以取消之前的Toast吗?

时间:2012-04-09 07:13:30

标签: android toast

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

问题是,吐司需要时间显示,当我滚动得足够快时,例如,我滚动到“2012/05”和“2012/06”并滚动到“2012/07”而没有停顿,我必须等待“2012/05”,“2012/06”,“2012/07”的Toast慢慢逐一显示。

似乎Android有一个不可见的队列来管理祝酒词

我该如何清洁并只显示最后一片吐司?我可以在不等待的情况下立即显示特定的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();

11 个答案:

答案 0 :(得分:22)

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

Boast课程完全符合您的需要。最近的代码可以在GitHub上找到:


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

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

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

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

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


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

}

答案 1 :(得分:15)

你只需要声明一个像这样的“Toast”var:

if (jsonString.indexOf(..) > 0) {
   //reading Person
} else {
   //reading SomeRandomObject
}

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

Toast toastMessage;

答案 2 :(得分:12)

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

toastObject.cancel()

答案 3 :(得分:5)

这是守则。

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

现在您可以使用toastobject的Object。它的Reference

toastobject.cancel();

您可以在线程中使用它,或者只要您想要关闭Toast。

答案 4 :(得分:4)

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

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

答案 5 :(得分: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();
}

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

showToast("message 1");

//一段时间后

showToast("message 2");

希望有帮助。

答案 6 :(得分:1)

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

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

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

答案 7 :(得分: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();
}

答案 8 :(得分:1)

简单。一旦你想创建另一个吐司,只需在吐司上调用方法.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. 

答案 9 :(得分: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();

    }

}

答案 10 :(得分:-1)

你可以使用一种射击技术。 Oke让我们开始定义:

private Toast mToast;
private showOnce=false;

后来当你想要举杯祝酒时:

if(showOnce==false){
  mToast=Toast.makeText(this, "Once!", Toast.LENGTH_LONG);
  mToast.show();
  showOnce=true;
}