Domanda

Quando si utilizza setDuration() per un Brindisi, è possibile impostare una lunghezza personalizzata o almeno qualcosa di più di Toast.LENGTH_LONG?

È stato utile?

Soluzione

I valori di LENGTH_SHORT e LENGTH_LONG sono 0 e 1. Questo significa che vengono trattati come bandiere anziché durate attuale quindi io non credo che sarà possibile impostare la durata a qualcosa di diverso da questi valori.

Se si desidera visualizzare un messaggio per l'utente più a lungo, si consideri un Notifica barra di stato . Barra di stato Le notifiche possono essere programmaticamente cancellate quando non sono più rilevanti.

Altri suggerimenti

Se si scava più in profondità nel codice Android, è possibile trovare le linee che indicano chiaramente, che non si può modificare la durata del messaggio Toast.

 NotificationManagerService.scheduleTimeoutLocked() {
    ...
    long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
    }

e valori di default per la durata sono

private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds

Si consiglia di provare:

for (int i=0; i < 2; i++)
{
      Toast.makeText(this, "blah", Toast.LENGTH_LONG).show();
}

di raddoppiare il tempo. Se si specifica 3 invece il 2 si triplicherà il time..etc.

La soluzione migliore per evitare effetti di dissolvenza tra i brindisi, che vengono lanciati in sequenza:

final Toast tag = Toast.makeText(getBaseContext(), "YOUR MESSAGE",Toast.LENGTH_SHORT);

tag.show();

new CountDownTimer(9000, 1000)
{

    public void onTick(long millisUntilFinished) {tag.show();}
    public void onFinish() {tag.show();}

}.start();

Qui il brindisi viene visualizzato circa 10 s.

Spero che questo aiuti.

Se si desidera un Toast a persistere, ho trovato è possibile incidere il vostro modo intorno ad esso avendo un Timer chiamata toast.show() ripetutamente (ogni secondo o giù di lì dovrebbe fare). Chiamando show() non si rompe nulla se il Toast sta già mostrando, ma lo fa aggiornare la quantità di tempo che rimane sullo schermo.

Ho sviluppato una classe personalizzata Toast con il quale è possibile mostrare Toast per una quantità desiderata di durata (in millisecondi)

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

public final class ToastHelper {

    private static final String TAG = ToastHelper.class.getName();

    public static interface OnShowListener {
        public void onShow(ToastHelper toast);
    }

    public static interface OnDismissListener {
        public void onDismiss(ToastHelper toast);
    }

    private static final int WIDTH_PADDING_IN_DIP = 25;
    private static final int HEIGHT_PADDING_IN_DIP = 15;
    private static final long DEFAULT_DURATION_MILLIS = 2000L;

    private final Context context;
    private final WindowManager windowManager;
    private View toastView;

    private int gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
    private int mX;
    private int mY;
    private long duration = DEFAULT_DURATION_MILLIS;
    private CharSequence text = "";
    private int horizontalMargin;
    private int verticalMargin;
    private WindowManager.LayoutParams params;
    private Handler handler;
    private boolean isShowing;
    private boolean leadingInfinite;

    private OnShowListener onShowListener;
    private OnDismissListener onDismissListener;

    private final Runnable timer = new Runnable() {

        @Override
        public void run() {
            cancel();
        }
    };

    public ToastHelper(Context context) {
        Context mContext = context.getApplicationContext();
        if (mContext == null) {
            mContext = context;
        }
        this.context = mContext;
        windowManager = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        init();
    }

    private void init() {
        mY = context.getResources().getDisplayMetrics().widthPixels / 5;
        params = new WindowManager.LayoutParams();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = android.graphics.PixelFormat.TRANSLUCENT;
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        params.setTitle("ToastHelper");
        params.alpha = 1.0f;
        // params.buttonBrightness = 1.0f;
        params.packageName = context.getPackageName();
        params.windowAnimations = android.R.style.Animation_Toast;
    }

    @SuppressWarnings("deprecation")
    @android.annotation.TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private View getDefaultToastView() {
        TextView textView = new TextView(context);
        textView.setText(text);
        textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
        textView.setClickable(false);
        textView.setFocusable(false);
        textView.setFocusableInTouchMode(false);
        textView.setTextColor(android.graphics.Color.WHITE);
        // textView.setBackgroundColor(Color.BLACK);
        android.graphics.drawable.Drawable drawable = context.getResources()
                .getDrawable(android.R.drawable.toast_frame);
        if (Build.VERSION.SDK_INT < 16) {
            textView.setBackgroundDrawable(drawable);
        } else {
            textView.setBackground(drawable);
        }
        int wP = getPixFromDip(context, WIDTH_PADDING_IN_DIP);
        int hP = getPixFromDip(context, HEIGHT_PADDING_IN_DIP);
        textView.setPadding(wP, hP, wP, hP);
        return textView;
    }

    private static int getPixFromDip(Context context, int dip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dip, context.getResources().getDisplayMetrics());
    }

    public void cancel() {
        removeView(true);
    }

    private void removeView(boolean invokeListener) {
        if (toastView != null && toastView.getParent() != null) {
            try {
                Log.i(TAG, "Cancelling Toast...");
                windowManager.removeView(toastView);
                handler.removeCallbacks(timer);
            } finally {
                isShowing = false;
                if (onDismissListener != null && invokeListener) {
                    onDismissListener.onDismiss(this);
                }
            }
        }
    }

    public void show() {
        if (leadingInfinite) {
            throw new InfiniteLoopException(
                    "Calling show() in OnShowListener leads to infinite loop.");
        }
        cancel();
        if (onShowListener != null) {
            leadingInfinite = true;
            onShowListener.onShow(this);
            leadingInfinite = false;
        }
        if (toastView == null) {
            toastView = getDefaultToastView();
        }
        params.gravity = android.support.v4.view.GravityCompat
                .getAbsoluteGravity(gravity, android.support.v4.view.ViewCompat
                        .getLayoutDirection(toastView));
        if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
            params.horizontalWeight = 1.0f;
        }
        if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
            params.verticalWeight = 1.0f;
        }
        params.x = mX;
        params.y = mY;
        params.verticalMargin = verticalMargin;
        params.horizontalMargin = horizontalMargin;

        removeView(false);
        windowManager.addView(toastView, params);
        isShowing = true;
        if (handler == null) {
            handler = new Handler();
        }
        handler.postDelayed(timer, duration);
    }

    public boolean isShowing() {
        return isShowing;
    }

    public void setDuration(long durationMillis) {
        this.duration = durationMillis;
    }

    public void setView(View view) {
        removeView(false);
        toastView = view;
    }

    public void setText(CharSequence text) {
        this.text = text;
    }

    public void setText(int resId) {
        text = context.getString(resId);
    }

    public void setGravity(int gravity, int xOffset, int yOffset) {
        this.gravity = gravity;
        mX = xOffset;
        mY = yOffset;
    }

    public void setMargin(int horizontalMargin, int verticalMargin) {
        this.horizontalMargin = horizontalMargin;
        this.verticalMargin = verticalMargin;
    }

    public long getDuration() {
        return duration;
    }

    public int getGravity() {
        return gravity;
    }

    public int getHorizontalMargin() {
        return horizontalMargin;
    }

    public int getVerticalMargin() {
        return verticalMargin;
    }

    public int getXOffset() {
        return mX;
    }

    public int getYOffset() {
        return mY;
    }

    public View getView() {
        return toastView;
    }

    public void setOnShowListener(OnShowListener onShowListener) {
        this.onShowListener = onShowListener;
    }

    public void setOnDismissListener(OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    public static ToastHelper makeText(Context context, CharSequence text,
            long durationMillis) {
        ToastHelper helper = new ToastHelper(context);
        helper.setText(text);
        helper.setDuration(durationMillis);
        return helper;
    }

    public static ToastHelper makeText(Context context, int resId,
            long durationMillis) {
        String string = context.getString(resId);
        return makeText(context, string, durationMillis);
    }

    public static ToastHelper makeText(Context context, CharSequence text) {
        return makeText(context, text, DEFAULT_DURATION_MILLIS);
    }

    public static ToastHelper makeText(Context context, int resId) {
        return makeText(context, resId, DEFAULT_DURATION_MILLIS);
    }

    public static void showToast(Context context, CharSequence text) {
        makeText(context, text, DEFAULT_DURATION_MILLIS).show();
    }

    public static void showToast(Context context, int resId) {
        makeText(context, resId, DEFAULT_DURATION_MILLIS).show();
    }

    private static class InfiniteLoopException extends RuntimeException {
        private static final long serialVersionUID = 6176352792639864360L;

        private InfiniteLoopException(String msg) {
            super(msg);
        }
    }
}

ho codificato in una classe di supporto per fare questo. È possibile vedere il codice a GitHub: https: // GitHub. com / quiqueqs / Toast-Expander / blob / master / src / com / thirtymatches / tostato / ToastedActivity.java

Questo è il modo che ci si visualizza un brindisi per 5 secondi (o 5000 millisecondi):

Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);

Lo so, sono un po 'in ritardo, ma ho preso la risposta di Regis_AG lo avvolse in una classe di supporto e funziona benissimo.

public class Toaster {
  private static final int SHORT_TOAST_DURATION = 2000;

  private Toaster() {}

  public static void makeLongToast(String text, long durationInMillis) {
    final Toast t = Toast.makeText(App.context(), text, Toast.LENGTH_SHORT);
    t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);

    new CountDownTimer(Math.max(durationInMillis - SHORT_TOAST_DURATION, 1000), 1000) {
      @Override
      public void onFinish() {
        t.show();
      }

      @Override
      public void onTick(long millisUntilFinished) {
        t.show();
      }
    }.start();
  }
}

Nel codice dell'applicazione, basta fare qualcosa di simile:

    Toaster.makeLongToast("Toasty!", 8000);

So che la risposta è abbastanza tardi .. Ho avuto lo stesso problema e ha deciso di implementare la mia versione di ossa nude Brindisi, dopo aver guardato nel codice sorgente di Android per i toast.

In sostanza è necessario creare un nuovo gestore di finestre, e mostrare e nascondere la finestra per la durata durata desiderata utilizzando un gestore

 //Create your handler
 Handler mHandler = new Handler();

//Custom Toast Layout
mLayout = layoutInflater.inflate(R.layout.customtoast, null);

//Initialisation 

mWindowManager = (WindowManager) context.getApplicationContext()
            .getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();

params.gravity = Gravity.BOTTOM
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = android.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;

Dopo l'inizializzazione del layout è possibile utilizzare il proprio nascondere e mostrare i metodi

    public void handleShow() {
    mWindowManager.addView(mLayout, mParams);
    }

    public void handleHide() {
        if (mLayout != null) {
            if (mLayout.getParent() != null) {
                mWindowManager.removeView(mLayout);
            }
                         mLayout = null;
        }

Ora tutto ciò che serve è quello di aggiungere due thread eseguibili che chiama il handleShow () e il handleHide (), che si potrebbe inviare al gestore.

    Runnable toastShowRunnable = new Runnable() {
        public void run() {
            handleShow();
        }
    };

 Runnable toastHideRunnable = new Runnable() {
        public void run() {
            handleHide();
        }
    }; 

e la parte finale

public void show() {

    mHandler.post(toastShowRunnable);
    //The duration that you want
    mHandler.postDelayed(toastHideRunnable, mDuration);

}

Questa è stata un'implementazione rapida e sporca .. non hanno preso alcuna prestazione in considerazione.

LONG_DELAY visualizzazione toast per 3.5 sec e SHORT_DELAY visualizzazione toast per 2 sec .

Toast utilizzare internamente INotificationManager e chiede è il metodo enqueueToast ogni volta che un Toast.show () viene chiamato.

Chiama lo show () con SHORT_DELAY due volte per accodare di nuovo lo stesso pane tostato. visualizzerà per 4 sec (2 sec + 2 sec).

Allo stesso modo, chiamare lo show () con LONG_DELAY due volte per accodare di nuovo lo stesso pane tostato. visualizzerà per 7 sec (3,5 sec + 3,5 sec)

Ecco una classe Toast personalizzato che ho fatto utilizzando il codice di cui sopra:

import android.content.Context;
import android.os.CountDownTimer;
import android.widget.Toast;

public class CustomToast extends Toast {
    int mDuration;
    boolean mShowing = false;
    public CustomToast(Context context) {
        super(context);
        mDuration = 2;
    }


    /**
     * Set the time to show the toast for (in seconds) 
     * @param seconds Seconds to display the toast
     */
    @Override
    public void setDuration(int seconds) {
        super.setDuration(LENGTH_SHORT);
        if(seconds < 2) seconds = 2; //Minimum
        mDuration = seconds;
    }

    /**
     * Show the toast for the given time 
     */
    @Override
    public void show() {
        super.show();

        if(mShowing) return;

        mShowing = true;
        final Toast thisToast = this;
        new CountDownTimer((mDuration-2)*1000, 1000)
        {
            public void onTick(long millisUntilFinished) {thisToast.show();}
            public void onFinish() {thisToast.show(); mShowing = false;}

        }.start();  
    }
}

Se avete bisogno di una lunga Brindisi, c'è una pratica alternativa, ma richiede l'utente a cliccare su un pulsante OK per farlo andare via. È possibile utilizzare un AlertDialog in questo modo:

String message = "This is your message";
new AlertDialog.Builder(YourActivityName.this)
    .setTitle("Optional Title (you can omit this)")
    .setMessage(message)
    .setPositiveButton("ok", null)
    .show();

Se si dispone di un messaggio lungo, è probabile che, non si sa quanto tempo ci vorrà per l'utente di leggere il messaggio, quindi a volte è una buona idea per richiedere il vostro utente a cliccare su un pulsante OK per continuare . Nel mio caso, io uso questa tecnica quando un utente fa clic sull'icona di un aiuto.

Come detto da altri Android brindisi può essere sia LENGTH_LONG o LENGTH_SHORT. Non v'è alcun modo per aggirare questo, non si dovrebbe seguire una qualsiasi delle 'hack' pubblicato.

Lo scopo di Brindisi sono per visualizzare le informazioni "non essenziali" e causa del loro effetto persistente, i messaggi può essere messo lontano fuori dal contesto se la loro durata supera una certa soglia. Se azionari Brindisi sono stati modificati in modo che possano visualizzare più di LENGTH_LONG il messaggio sarebbe soffermarsi sullo schermo fino a quando il processo dell'applicazione viene terminata come viste pane tostato vengono aggiunti alla WindowManager e non un ViewGroup nella vostra applicazione. Vorrei assumere questo è il motivo per cui è codificato duro.

Se è assolutamente necessario per mostrare un messaggio di stile brindisi più di tre secondi e mezzo vi consiglio di costruire una visione che viene collegato al contenuto del Activity, in questo modo scompare quando l'utente chiude l'applicazione. Il mio SuperToasts offerte biblioteca con questo problema e molti altri, si sentono liberi di usarlo! Si sarebbe molto probabilmente interessati a utilizzare SuperActivityToasts

Basta usare SuperToast per fare un elegante brindisi in qualsiasi situazione. Fai la tua brindisi colorato . Modifica il tuo font color e anche che è dimensione . Spero che sarà tutto in uno per voi.

Perché mangiare pane tostato, quando si può avere l'intero Snackbar : https://developer.android.com/reference/android/support/design/widget/Snackbar.html

Snackbar> Brindisi, personalizzati Brindisi, Crostino di pane

Ecco un metodo molto semplice, che ha lavorato per me:

for (int i=0; i < 3; i++) { Toast.makeText(this, "MESSAGE", Toast.LENGTH_SHORT).show(); }

La durata del LENGTH_SHORT di 2 secondi ed LENGTH_LONG è di 3,5 secondi, Qui verrà mostrato il messaggio brindisi per 6 secondi dal momento che è racchiuso in un ciclo for. Ma un inconveniente di questo metodo è dopo ogni 2 secondi un piccolo effetto di dissolvenza può sorgere. ma non è molto evidente. La speranza è utile

L'utente non può custome definita la durata del Toast. perché la funzione di NotificationManagerService scheduleTimeoutLocked () non usa la durata campo. il codice sorgente è il seguente.

private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
    {
        Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
        long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
        mHandler.removeCallbacksAndMessages(r);
        mHandler.sendMessageDelayed(m, delay);
    }

Usa Crostino di pane, si tratta di una libreria di Toast molto flessibile.

Crostino

Si può usare come brindisi:

Crouton.makeText(context, "YOUR_MESSAGE", Style.INFO);

o si può anche andare un po 'più profondo e personalizzarlo di più, come l'impostazione del tempo all'infinito! per esempio qui voglio mostrare un messaggio brindisi fino a quando l'utente prende atto facendo clic su di esso.

private static void showMessage(final Activity context, MessageType type, String header, String message) {
    View v = context.getLayoutInflater().inflate(R.layout.toast_layout, null);
    TextView headerTv = (TextView) v.findViewById(R.id.toastHeader);
    headerTv.setText(header);
    TextView messageTv = (TextView) v.findViewById(R.id.toastMessage);
    messageTv.setText(message);
    ImageView toastIcon = (ImageView) v.findViewById(R.id.toastIcon);

    final Crouton crouton = getCrouton(context, v);
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Crouton.hide(crouton);
        }
    });

    crouton.show();
}

private static Crouton getCrouton(final Activity context, View v) {
    Crouton crouton = Crouton.make(context, v);
    crouton.setConfiguration(new Configuration.Builder().setDuration(Configuration.DURATION_INFINITE).build());
    return crouton;
}

Layout Custome che verrà gonfiato per il brindisi.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:background="@drawable/shadow_container"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="@dimen/default_margin"
    tools:ignore="Overdraw">

    <ImageView
        android:id="@+id/toastIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/default_spacing_full"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/toastHeader"
            style="@style/ItemText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/toastMessage"
            style="@style/ItemSubText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>

Un brindisi con sfondo personalizzato e vista ha fatto il trucco per me. L'ho provato in tablet Nexus 7 e ho notato nessuna animazione dissolvenza fadein durante il ciclo. Heres l'attuazione:

public static void customToast(Context context, String message, int duration) {

    for (int i = 0; i < duration; i++) {
        Toast toast = new Toast(context);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.toast_layout, null);
        TextView textViewToast = (TextView) view
                .findViewById(R.id.textViewToast);
        textViewToast.setText(message);
        toast.setView(view);
        toast.show();
    }

}

Ecco il TextView personalizzato utilizzato nel codice di cui sopra:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/fragment_background"
android:padding="8dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/blue" />

@ drawable / fragment_background sta facendo il mio pane tostato hanno arrotondato angolo, come nella versione KitKat. È possibile aggiungere altre viste anche nel file. Eventuali modifiche di miglioramento e commenti sono incoraggiati come io sto progettando di implementare questo nella mia app dal vivo.

Pianificare un conto alla rovescia fino a quando un tempo in futuro, con le notifiche regolari intervalli lungo la strada. Esempio di mostrare un secondo conto alla rovescia di 30 in un campo di testo:

     new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();


durata Toast può essere violato utilizzando un filo che corre il brindisi in esclusiva. Questo funziona (corre il brindisi per 10 secondi, modificare sospensione e CTR a proprio piacimento):

final Toast toast = Toast.makeText(this, "Your Message", Toast.LENGTH_LONG);

Thread t = new Thread(){
    public void run(){
          int ctr = 0;
          try{
               while( ctr<10 ){
                    toast.show();
                    sleep(1000);
                    ctr++;
               }
          } catch (Exception e) {
               Log.e("Error", "", e);
          }
     }
 };
 t.start();

Questo testo scompare in 5 secondi.

    final Toast toast = Toast.makeText(getApplicationContext(), "My Text", Toast.LENGTH_SHORT);
    toast.show();

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               toast.cancel(); 
           }
    }, 5000); // Change to what you want

Modifica: Come Itai Spector in commento ha detto che sarà visualizzato per circa 3,5 secondi, quindi utilizzare questo codice:

    int toastDuration = 5000; // in MilliSeconds
    Toast mToast = Toast.makeText(this, "My text", Toast.LENGTH_LONG);
    CountDownTimer countDownTimer;
    countDownTimer = new CountDownTimer(toastDuration, 1000) {
        public void onTick(long millisUntilFinished) {
            mToast.show();
        }

        public void onFinish() {
            mToast.cancel();
        }
    };

    mToast.show();
    countDownTimer.start();

Un approccio molto semplice per la creazione di un tempo leggermente più lungo messaggio è il seguente:

private Toast myToast;

public MyView(Context context) {
  myToast = Toast.makeText(getContext(), "", Toast.LENGTH_LONG);
}

private Runnable extendStatusMessageLengthRunnable = new Runnable() {
  @Override
    public void run() {
    //Show the toast for another interval.
    myToast.show();
   }
}; 

public void displayMyToast(final String statusMessage, boolean extraLongDuration) {
  removeCallbacks(extendStatusMessageLengthRunnable);

  myToast.setText(statusMessage);
  myToast.show();

  if(extraLongDuration) {
    postDelayed(extendStatusMessageLengthRunnable, 3000L);
  }
}

Si noti che l'esempio di cui sopra, elimina la LENGTH_SHORT opzione per mantenere l'esempio semplice.

È in genere non si desidera utilizzare un Brindisi messaggio per la visualizzazione dei messaggi molto lunghi intervalli di tempo, in quanto non è questo il Brindisi classe' scopo.Ma ci sono momenti in cui la quantità di testo che si desidera visualizzare potrebbe prendere più di 3,5 secondi per leggere, e in questo caso una leggera estensione di tempo (ad esempio, a 6,5 secondi, come mostrato sopra), IMO, essere utile e coerente con la destinazione d'uso.

Imposta brindisi per un determinato periodo in millisecondi:

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

Dopo aver fallito con ogni soluzione disponibile, ho avuto finalmente soluzione utilizzando la ricorsione.

Codice:

//Recursive function, pass duration in seconds
public void showToast(int duration) {
    if (duration <= 0)
        return;

    Toast.makeText(this, "Hello, it's a toast", Toast.LENGTH_LONG).show();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            showToast(duration-1);
        }
    }, 1000);
}

No, e la maggior parte / tutti gli hack qui elencate non funzionano più in Android 9. Ma c'è una soluzione molto migliore. Se si messaggio deve rimanere in giro, utilizzare una finestra di dialogo

(new AlertDialog.Builder(this)).setTitle("Sorry!")
.setMessage("Please let me know by posting a beta comment on the play store .")
.setPositiveButton("OK", null).create().show();
Toast.makeText(this, "Text", Toast.LENGTH_LONG).show(); 
Toast.makeText(this, "Text", Toast.LENGTH_LONG).show();

Una soluzione molto semplice al problema. Due o tripla di esse vi farà Toast durare più a lungo. E 'l'unico modo per aggirare.

È possibile impostare il tempo desiderato in millisecondi nel metodo Toast.makeText(); in questo modo:

//40 seconds
long mToastLength = 40*1000 
//this toast will be displayed for 40 seconds.
Toast.makeText(this, "Hello!!!!!", mToastLength).show(); 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top