¿Puedo cancelar Toast anterior cuando quiero mostrar otro Toast?

En mi aplicación, construyo un widget de calendario para mi actvity, cuando lo desplazo al mes anterior o siguiente, lo dejo hacer un brindis y mostrarlo.

La pregunta es, el brindis necesitan tiempo para mostrar, cuando lo despliegue lo suficientemente rápido, por ejemplo, me desplacé a "2012/05" y "2012/06" y desplácese a "2012/07" sin pausa, tengo que esperar El Toast de "2012/05", "2012/06", "2012/07" para mostrar uno por uno lentamente.

Parece que android tiene una cola invisible para administrar brindis

¿Cómo puedo limpiarlo y sólo mostrar el último brindis? ¿Puedo mostrar un tostado específico inmediatamente sin esperar?

Busqué en el "android.widget.Toast.java" y encontrar un método "cancel ()", pero lamentablemente no funciona como sigue.

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

Es necesario llamar al método en el objeto correcto.

 toastObject.cancel() 

Aquí está mi respuesta copiada de otra pregunta similar aquí:

  • Android cancela Toast al salir de la aplicación y cuando se muestra el brindis

La clase Boast logra exactamente lo que necesita. El código más reciente se puede encontrar en GitHub aquí:

  • Boast.java

El truco es hacer un seguimiento de la última Toast que se mostró, y cancelar esa.

Lo que he hecho es crear un contenedor de Toast , que contiene una referencia estática al último Toast que se muestra.

Cuando necesito mostrar una nueva, primero cancelo la referencia estática, antes de mostrar la nueva (y guardarla en la estática).

Aquí está el código completo de la envoltura de Boast que hice – imita bastante de los métodos de la tostada para que lo utilice. De forma predeterminada, el Boast cancelará el anterior, por lo que no creará una cola de Tostadas esperando a que se muestre.

Si solo quieres saber cómo cancelar las notificaciones al salir de tu aplicación, encontrarás mucha ayuda allí.


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

Sólo tienes que declarar un "Toast" var como este:

 Toast toastMessage; 

Entonces en tu función, hazlo así:

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

Aquí está el código.

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

Ahora puede utilizar el objeto de toastobject. Su referencia

 toastobject.cancel(); 

Puede usarlo en Thread o cuando quiera cerrar el Toast.

Toast tiene un método para ocultar el mensaje de brindis actual

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

Intente llamar a t.cancel () cuando sea necesario.

Usted puede reutilizar una tostada, esto hará que se muestre inmediatamente.

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

Puede crear un método estático y usarlo para mostrar un brindis:

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

Sencillo. Simplemente llame al método .cancel () en el brindis una vez que desee crear otro brindis.

Comience por definir una variable Toast en la parte superior de su clase como esta

 private Toast mToast; 

Más tarde, cuando desee crear un nuevo Toast (y hacer desaparecer el antiguo), haga esto.

 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. 
  • Cancelar un brindis ya abierto en Android
  • ¿Es posible especificar la posición de un Toast?
  • Cómo personalizar backgroud, color de fondo y color de texto para Toast en android
  • ¿Cómo mostrar tostadas dentro del temporizador?
  • Problema con Toast en llamada AsyncTask método
  • Toast.makeText (...) .show () es a veces mal alineado
  • Tostada personalizada en android: un ejemplo sencillo
  • Cómo establecer el tiempo de visualización de Toast menos de Toast.LENGTH_SHORT
  • Problema de brindis en android
  • Cómo cancelar Toast creado en un método diferente en android?
  • Detener una tostada y empezar otra en android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.