如何防止多个Toast Overlaps

时间:2012-10-16 19:58:14

标签: android toast

我一直在使用常见的“myToast”,我在发布新的吐司之前使用“myToast.cancel()。对于Android v2.3及更早版本,这非常有用。当需要发送新的吐司时,旧的,如果仍在屏幕上,则被取消(并立即消失)以替换为新的吐司。如果用户多次按下需要警报的键(和其他条件),这可以避免堆叠一堆吐司我的实际情况是,当按下错误的键时会出现一个吐司,如果没有按下清除键,则会出现另一个吐司。

对于Android 4.0和4.1,在下一个toast之前发出myToast.cancel()会杀死当前和下一个toast。当前cancel() API确实表明它取消了当前和下一个toast(这似乎相当愚蠢)。为什么要取消你想要的吐司?

任何关于取消Android版本(及其在v2.3及更早版本中的工作方式)的工作的想法一致吗?

我会尝试一些不道德的双重吐司系统跟踪正在使用的吐司,但似乎这种痛苦解决了4.x中的这种不良行为,以便在旧的Android版本中获得完美和逻辑的功能。


好的,我解决了它,但它并不像我希望的那样干净。我实施了双重吐司方法,它在两个吐司之间交替。首先,我们在OnCreate

之前定义活动的祝酒词
Toast toast0;
Toast toast1;
private static boolean lastToast0 = true;

在OnCreate中:

toast0 = new Toast(getApplicationContext());
toast0.cancel();
toast1 = new Toast(getApplicationContext());
toast1.cancel();

最后,当我需要同时显示吐司并取消之前的吐司时,我会使用类似的东西:

if (lastToast0) {
    toast0.cancel();
    toast1.setDuration(Toast.LENGTH_LONG);
    toast1.setText("new message");
    toast1.show();
    lastToast0 = false;
} else {
    toast1.cancel();
    toast0.setDuration(Toast.LENGTH_LONG);
    toast0.setText("new message");
    toast0.show();
    lastToast0 = true;
}

如果你需要取消现有的吐司(在它超时之前),请使用:

toast0.cancel();
toast1.cancel();

在Nexus 7(4.1),Emulator 4.0以及Android 2.2,2.3的多个设备上进行了测试。

8 个答案:

答案 0 :(得分:49)

而不是致电cancel()。尝试重置文字并致电show()。这应该取消最后一个吐司

myToast.setText("wrong key")
myToast.show();

如果你继续使用相同的myToast而不是每次都创建一个,我猜他们不会叠加。

答案 1 :(得分:3)

nandeesh的解决方案不适合你吗? 他的解决方案比使用两种不同的吐司更清洁。

例如,在onCreate之前(扩展他/她的答案),我们宣布吐司:

private Toast myToast;

在onCreate中我们必须使用makeToast初始化它(否则我们会收到错误):

myToast = Toast.makeText(getApplicationContext(), null, Toast.LENGTH_SHORT);

每当我们想要举杯祝酒时,我们只需致电:

myToast.setText("some text");
myToast.show();

这将正确取代之前的吐司。

答案 2 :(得分:2)

cancel()我不担心做任何事情。

我建议使用Crouton https://github.com/keyboardsurfer/Crouton

答案 3 :(得分:2)

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

Boast课程完全符合您的需要。


诀窍是跟踪显示的最后一个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();
    }

}

答案 4 :(得分:1)

我的解决方案适用于4. *和2.3 Android版本

static Toast toast;
.....

if (toast != null)
    toast.cancel();

boolean condition = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
if ((toast == null && condition) || !condition)
    toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
if ((toast != null && condition))
    toast.setText(text);
toast.show();

答案 5 :(得分:1)

创建Toast对象:

Toast toastobject=null;

现在使用以下代码显示吐司。这对我来说很有用

    int index = clickCounter-1;


    if(toastobject!= null)
            {
                toastobject.cancel();
            }
            toastobject = Toast.makeText(this,"Toast Text" , Toast.LENGTH_SHORT);
            listItems.remove(index);
            toastobject.show();

答案 6 :(得分:0)

创建新功能并调用它。

ImageButton ABtn = (ImageButton) findViewById(R.id.Btn);
ABtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{       
SETToast("mytext");
}
});

    private Toast toast = null;

public void SETToast( String text)
{
  if(toast==null)
  {
     toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT); 
     toast.show();
     final Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            toast=null;
        }
     }, 2000);
  }
  else
  {
      toast.setText(text);
  }   
}

答案 7 :(得分:0)

将Java类设置为 ShowToast.java ,如下所示

    public class ShowToast {

        private static Toast toast;

        public static void show(Context mcontext, String text) {
            if (toast != null) 
               toast.cancel();
            toast = Toast.makeText(mcontext, text, Toast.LENGTH_SHORT);
            toast.show();
        }
    }

然后将其命名为

    ShowToast.show(getApplicationContext(),"YOUR_TOAST_TEXT");