usar studio maketext como android toast

maketext - como usar toast en android studio



¿Puedo cancelar Toast anterior cuando quiero mostrar otro Toast? (11)

En mi aplicación, construyo un widget de calendario para mi actividad, cuando lo desplazo al mes anterior o el próximo, lo dejo y lo muestro.

La pregunta es, la tostada necesita tiempo para mostrar, cuando la desplazo lo suficientemente rápido, por ejemplo, me desplazo a "2012/05" y "2012/06" y me desplazo a "2012/07" sin pausa, tengo que esperar el brindis de "2012/05", "2012/06", "2012/07" para mostrar uno por uno lentamente.

Parece que Android tiene una cola invisible para administrar los brindis

¿Cómo puedo limpiarlo y solo mostrar la última tostada? ¿Puedo mostrar una tostada específica inmediatamente sin esperar?

Busqué en "android.widget.Toast.java" y encontré un método cancel() , pero desafortunadamente no funciona de la siguiente manera.

if (t != null) { t.cancel(); } t = Toast.makeText(this.mContext, mHelper.getYear() + "年" + (mHelper.getMonth() + 1) + "月", Toast.LENGTH_SHORT); t.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 puedes usar el Objeto de toastobject. Su Reference

toastobject.cancel();

Puede usarlo en Hilo o cuando quiera Cerrar el Toast.


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

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

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

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

Lo que he hecho es crear un contenedor Toast , que contiene una referencia estática a la última 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 del envoltorio Boast que hice: imita suficientes métodos Toast para que lo use. De forma predeterminada, el Boast cancelará el anterior, por lo que no creará una cola de brindis en espera de ser mostrada.

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


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

toastObject.cancel()


Hay muchas formas en que podemos cancelar Toast anteriores cuando queremos mostrar otro Toast. A continuación he escrito una manera simple y sencilla de implementarlo. En primer lugar, tenemos que crear una variable a la que se pueda acceder en toda la clase.

private Toast toast;

Después de crear la variable a la que puede acceder toda la clase, tenemos que crear un método en nuestra clase que muestre el mensaje de brindis y verifique si el brindis anterior se muestra y luego cancelarlo.

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

puede cambiar el mensaje de tostada en tiempo de ejecución llamando al método anterior.

showToast("message 1");

//después de algún tiempo

showToast("message 2");

Espero eso ayude.


Puede reutilizar un brindis, esto lo hará mostrar inmediatamente.

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


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


Puedes usar una técnica de disparo. Oke vamos a empezar a definir:

private Toast mToast; private showOnce=false;

Más tarde, cuando quieras mostrar tostadas una vez:

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


Sencillo. Simplemente llame al método .cancel () en la tostada una vez que desee crear otra tostada.

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

private Toast mToast;

Más tarde, cuando quieras crear una tostada nueva (y que desaparezca la anterior), haz 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.


Solo necesitas declarar una var "Toast" como esta:

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


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.


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