2013-01-24 20 views
19

Questo è il modo in cui devo mostrare lo Toast per 500 millisecondi. Però, sta mostrando più di un secondo.Come posso visualizzare un brindisi per una durata specifica?

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

Come posso mostrare Toast solo per 500 millisecondi?

+0

letto il doc. l'ultimo parametro può assumere solo valori predefiniti, non è in millis. – njzk2

+0

[È possibile visualizzare il brindisi finché necessario] (http://stackoverflow.com/a/20373743/726863) –

+0

Possibile duplicato di [È possibile che un toast Android sia più lungo di "Toast.LENGTH \ _LONG"?] (Http : //stackoverflow.com/questions/2220560/can-an-android-toast-be-longer-than-toast-length-long) –

risposta

63

Questo non può essere fatto. Per mostrare un brindisi per una lunghezza inferiore a Toast.LENGTH_SHORT, è necessario annullarlo dopo l'orario desiderato. Qualcosa di simile:

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); 
+0

Grazie per i tuoi suggerimenti. Funziona perfettamente. Molte grazie. – MuraliGanesan

+0

@Muraliganesan Si prega di accettare la risposta se ha risolto il problema –

+0

[Questo può essere fatto di sicuro!] (Http://stackoverflow.com/a/20373743/726863) –

0

Non credo che ciò possa essere fatto, è possibile utilizzare solo Toast.LENGTH_LONG o Toast.LENTH_SHORT non è possibile definire la propria velocità.

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

Questo è l'unico modo in cui si può ..

1

Impossibile fare quello che stai chiedendo con i toast standard. Forse dovresti pensare all'integrazione di una libreria di terze parti che ti offre migliori opzioni di Toast (chiamate Crouton). Non l'ho usato da solo, ma alla gente sembra piacere.

Non è possibile controllare la durata di Toasts nel sistema operativo standard.

collegamento Crostino: https://github.com/keyboardsurfer/Crouton

1

Questo non può essere fatto. I valori di Toast.LENGTH_SHORT e Toast.LENGTH_LONG sono 0 e 1. Ciò significa che vengono considerati come flag anziché durate effettive, quindi non penso che sarà possibile impostare la durata su valori diversi da questi valori.

0

Provalo prima. Questo imposta su un periodo specifico in milli-secondi:

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); 
     } 
    } 
} 
+0

aggiungendo '2000' a' non sarò sicuro che il tempo sia passato .. devi usare l'orologio invece –

+0

non puoi contare che aggiungere '2000' a' i' aggiungerà '2 secondi', dipende dalla velocità del dispositivo. Se si desidera eseguire il ciclo fino al momento in cui è necessario eseguire operazioni come 'while ((System.currentTimeMillis() - startTime) <2000))'. Questo è basilare in ogni linguaggio di programmazione .. mai diverso dalla base dei tempi nell'intervallo del ciclo. –

2

Ho trovato this answer. Anche se un po 'più complesso, consente anche di creare toast più lunghi di Toast.LENGTH_LONG. Potrebbe essere necessario modificare la durata del tick da 1000ms a 500ms.

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

Ecco come funziona: il conto alla rovescia ha un tempo di notifica più breve rispetto alla durata per la quale viene visualizzato il brindisi in base alla bandiera, in modo che il pane può essere mostrato ancora una volta se il conto alla rovescia non è finito. Se il pane tostato viene nuovamente visualizzato mentre è ancora sullo schermo, rimarrà lì per l'intera durata senza lampeggiare. Al termine del conto alla rovescia, il brindisi viene annullato per nasconderlo anche se la durata della visualizzazione non è terminata.

Questo funziona anche se il brindisi deve essere visualizzato per una durata inferiore alla durata predefinita: il primo brindisi visualizzato verrà semplicemente annullato al termine del conto alla rovescia.

1

Questo sta funzionando bene per me.

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

il conto alla rovescia viene utilizzato per visualizzare un messaggio di brindisi per una durata specifica.

3

Aggiungendo a @ risposta di Senth, se non abituato a accumulare il tempo in cui si chiama il metodo showToast più volte, con lo stesso messaggio:

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

È possibile visualizzare brindisi ora 500 ms come questo:

showToast("Not Allowed", 500); 
0

ho provato metodo diverso e questo metodo funziona per me

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 
Problemi correlati