utilizar usar studio method maketext example como cannot agregar android toast android-toast

android - usar - ¿Cómo puedo mostrar un brindis por una duración específica?



toast android xamarin (12)

Agregando a la respuesta de @ Senth, si no acostumbra acumular el tiempo cuando llama al método showToast varias veces, con el mismo mensaje:

private Toast mToastToShow = null; String messageBeingDisplayed = ""; /** * Show Toast message for a specific duration, does not show again if the message is same * * @param message The Message to display in toast * @param timeInMSecs Time in ms to show the toast */ public void showToast(String message, int timeInMSecs) { if (mToastToShow != null && message == messageBeingDisplayed) { Log.d("DEBUG", "Not Showing another Toast, Already Displaying"); return; } else { Log.d("DEBUG", "Displaying Toast"); } messageBeingDisplayed = message; // Set the toast and duration int toastDurationInMilliSeconds = timeInMSecs; mToastToShow = Toast.makeText(this, message, Toast.LENGTH_LONG); // Set the countdown to display the toast CountDownTimer toastCountDown; toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, timeInMSecs /*Tick duration*/) { public void onTick(long millisUntilFinished) { if (mToastToShow != null) { mToastToShow.show(); } } public void onFinish() { if (mToastToShow != null) { mToastToShow.cancel(); } // Making the Toast null again mToastToShow = null; // Emptying the message to compare if its the same message being displayed or not messageBeingDisplayed = ""; } }; // Show the toast and starts the countdown mToastToShow.show(); toastCountDown.start(); }

Puede mostrar tostadas ahora por 500 ms así:

showToast("Not Allowed", 500);

Esta es la forma en que tengo que mostrar el Toast por 500 milisegundos. Sin embargo, está mostrando más de un segundo.

Toast.makeText(LiveChat.this, "Typing", 500).show();

¿Cómo puedo mostrar Toast solo por 500 milisegundos?


Encontré esta respuesta . Aunque un poco más complejo, también le permite crear brindis más largos que Toast.LENGTH_LONG. Es posible que tenga que cambiar la duración de la marca de 1000 ms a 500 ms.

private Toast mToastToShow; public void showToast(View view) { // Set the toast and duration int toastDurationInMilliSeconds = 10000; mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG); // Set the countdown to display the toast CountDownTimer toastCountDown; toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) { public void onTick(long millisUntilFinished) { mToastToShow.show(); } public void onFinish() { mToastToShow.cancel(); } }; // Show the toast and starts the countdown mToastToShow.show(); toastCountDown.start(); }

Así es como funciona: la cuenta regresiva tiene un tiempo de notificación más corto que el tiempo durante el cual se muestra el brindis de acuerdo con la bandera, por lo que se puede mostrar nuevamente si la cuenta regresiva no ha terminado. Si se vuelve a mostrar el brindis mientras aún está en la pantalla, permanecerá allí durante toda la duración sin parpadear. Cuando finaliza la cuenta atrás, el brindis se cancela para ocultarlo incluso si la duración de la visualización no ha terminado.

Esto funciona incluso si la tostada debe mostrarse durante un período más corto que la duración predeterminada: la primera tostada que se muestra simplemente se cancelará cuando finalice la cuenta atrás.


Este está funcionando bien para mí.

final Toast mToastToShow; int toastDurationInMilliSeconds = 10000; mToastToShow = Toast.makeText(getApplicationContext(), "Snapshot Saved Successfully.",Toast.LENGTH_LONG); // Set the countdown to display the toast CountDownTimer toastCountDown; toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) { public void onTick(long millisUntilFinished) { mToastToShow.show(); } public void onFinish() { mToastToShow.cancel(); } }; // Show the toast and starts the countdown mToastToShow.show(); toastCountDown.start();

La cuenta atrás se usa para mostrar un mensaje de brindis por una duración específica.


Esto no se puede hacer. Los valores de Toast.LENGTH_SHORT y Toast.LENGTH_LONG son 0 y 1. Esto significa que se tratan como indicadores en lugar de duraciones reales, por lo que no creo que sea posible establecer la duración en otra cosa que no sean estos valores.


Esto no se puede hacer. Para mostrar una tostada para una longitud más corta que Toast.LENGTH_SHORT , debe cancelarla después del tiempo que desee. Algo como:

final Toast toast = Toast.makeText(getApplicationContext(), "This message will disappear in half a second", Toast.LENGTH_SHORT); toast.show(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { toast.cancel(); } }, 500);


He creado una clase ToastMessage en lado droide.

public class ToastMessage: IToast { public void LongAlert(string message) { Toast toast = Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short); toast.Show(); Device.StartTimer(TimeSpan.FromSeconds(0.5), () => { toast.Cancel(); return false; }); } }

He creado la interfaz IToast

public interface IToast { void LongAlert(string message); }

Servicio de llamadas por dependencia

DependencyService.Get<IToast>().LongAlert("Right Answer");


No creo que se pueda hacer esto, solo puedes usar Toast.LENGTH_LONG o Toast.LENTH_SHORT no puedes definir tu velocidad conocida.


No puedes hacer lo que estás pidiendo con los brindis estándar. Tal vez debería pensar en integrar una biblioteca de terceros que le ofrezca mejores opciones de Toast (llamado Crouton). Yo no lo he usado, pero a la gente parece gustarle.

No puedes controlar la longitud de Toast en el sistema operativo estándar.

Enlace de crouton: https://github.com/keyboardsurfer/Crouton


Probé un método diferente y este método funciona para mí.

final Toast mytoast = Toast.makeText(getApplicationContext(), jsonObject.getString("response_message"), Toast.LENGTH_SHORT); mytoast.show(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mytoast.cancel(); } }, 5000);// 5 sec


Pruébalo primero. Esto establece el brindis por un período específico en milisegundos:

public void toast(int millisec, String msg) { Handler handler = null; final Toast[] toasts = new Toast[1]; for(int i = 0; i < millisec; i+=2000) { toasts[0] = Toast.makeText(this, msg, Toast.LENGTH_SHORT); toasts[0].show(); if(handler == null) { handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { toasts[0].cancel(); } }, millisec); } } }


También puede modificar el patrón del ejemplo Toast.LENGTH_LONG :

Toast.makeText(getBaseContext(),"your message",Toast.LENGTH_LONG*3).show();

Recordando que el patrón tiene una duración de 1 segundo.


Toast.makeText(LiveChar.this,"Typing",Toast.LENGTH_SHORT);

Esta es la única forma en que puede ..