Question

Lors de l'utilisation setDuration () pour porter un toast, est-il possible de définir une longueur personnalisée ou au moins quelque chose de plus que Toast.LENGTH_LONG?

Était-ce utile?

La solution

Les valeurs de LENGTH_SHORT et de LENGTH_LONG sont 0 et 1. Cela signifie qu'ils sont traités comme des drapeaux plutôt que des durées réelles de sorte que Je ne pense pas qu'il sera possible de régler la durée à autre chose que ces valeurs.

Si vous souhaitez afficher un message à l'utilisateur pour plus, envisager une barre d'état notification . Barre d'état Les notifications peuvent être annulées par programme quand ils ne sont plus pertinents.

Autres conseils

Si vous creusez plus profond dans le code Android, vous pouvez trouver les lignes qui indiquent clairement, que nous ne pouvons pas changer la durée du message de Toast.

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

et les valeurs par défaut pour la durée sont

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

Vous pouvez essayer:

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

pour doubler le temps. Si vous spécifiez 3 au lieu de 2, il triplera le time..etc.

La meilleure solution pour éviter les effets d'évanouissement entre les toasts qui sont lancés dans l'ordre:

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

Ici, le pain est affiché environ 10 s.

Hope this helps.

Si vous voulez un Toast à persister, je trouve que vous pouvez pirater votre chemin en ayant un Timer d'appel toast.show() à plusieurs reprises (toutes les secondes devriez faire). L'appel show() ne casse rien si le Toast montre déjà, mais il ne rafraîchit la quantité de temps qu'il reste à l'écran.

J'ai développé une classe personnalisée Toast avec lequel vous pouvez afficher Toast pour une quantité désirée de la durée (en secondes Milli)

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

J'ai codé une classe d'aide pour ce faire. Vous pouvez voir le code sur GitHub: https: // GitHub. com / quiqueqs / Toast-expanseur / blob / maître / src / com / thirtymatches / grillé / ToastedActivity.java

Voici comment vous afficher un toast pendant 5 secondes (ou 5000 millisecondes):

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

Je sais que je suis un peu en retard, mais je pris la réponse de Regis_AG et enveloppé dans une classe d'aide et il fonctionne très bien.

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

Dans votre code d'application, il suffit de faire quelque chose comme ceci:

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

Je sais que la réponse est assez tard .. J'ai eu le même problème et a décidé de mettre en œuvre ma propre version de Toast nue os, après avoir regardé dans le code source Android pour le pain grillé.

Fondamentalement, vous devez créer un nouveau gestionnaire de fenêtres, et afficher et masquer la fenêtre pendant toute la durée de la durée souhaitée à l'aide d'un gestionnaire

 //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;

Après l'initialisation de la mise en page, vous pouvez utiliser vos propres méthodes de masquer et d'afficher

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

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

Maintenant, tout ce dont vous avez besoin est d'ajouter deux threads exécutables qui appelle la handleShow () et le handleHide () que vous pouvez poster au gestionnaire.

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

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

et la partie finale

public void show() {

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

}

Ce fut une mise en œuvre rapide et sale .. Ont pris aucune exécution en considération.

LONG_DELAY pain grillé affichage pour 3,5 s et SHORT_DELAY affichage de pain grillé pour 2 s .

Toast utiliser en interne INotificationManager et demande c'est la méthode enqueueToast chaque fois qu'un Toast.show () est appelée.

Appelez le spectacle () avec SHORT_DELAY sera à nouveau enqueue même pain grillé deux fois. il affiche pour 4 s (2 s + 2 s).

De même, appelez le spectacle () avec LONG_DELAY sera à nouveau enqueue même pain grillé deux fois. il affiche pour 7 s (3,5 + 3,5 sec sec)

Voici une classe Toast personnalisée j'ai fait à l'aide du code ci-dessus:

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

Si vous avez besoin d'une longue Toast, il y a une alternative pratique, mais il exige que votre utilisateur de cliquer sur un bouton OK pour faire disparaître. Vous pouvez utiliser un AlertDialog comme ceci:

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

Si vous avez un long message, les chances sont, vous ne savez pas combien de temps il faudra pour que votre utilisateur de lire le message, donc il est parfois une bonne idée d'exiger de votre utilisateur de cliquer sur un bouton OK pour continuer . Dans mon cas, j'utilise cette technique lorsqu'un utilisateur clique sur une icône d'aide.

Comme mentionné par d'autres Android Toasts peuvent être soit LENGTH_LONG ou LENGTH_SHORT. Il n'y a pas moyen de contourner cela, vous ne devriez suivre l'un des « hacks » affiché.

Le but de Toasts doivent afficher des informations « non essentiels » et en raison de leur effet persistant, les messages peuvent être mis loin du contexte si leur durée dépasse un certain seuil. Si le stock Toasts ont été modifiés de manière à pouvoir afficher plus de LENGTH_LONG le message s'attarder sur l'écran jusqu'à ce que le processus de l'application est terminée que des vues de pain grillé sont ajoutés à la WindowManager et non un ViewGroup dans votre application. Je suppose que c'est la raison pour laquelle il est codé en dur.

Si vous devez absolument montrer un message de style de pain grillé plus de trois secondes et demie, je recommande la construction d'une vue qui se joint au contenu de l'activité, de cette façon il disparaîtra lorsque l'utilisateur quitte l'application. Ma bibliothèque SuperToasts les traite de cette question et bien d'autres, ne hésitez pas à l'utiliser! Vous seriez très probablement intéressé à utiliser SuperActivityToasts

Il suffit d'utiliser SuperToast pour faire un pain grillé élégant sur toute situation. Faites votre pain grillé coloré . Modifier votre couleur de la police et aussi est Taille . Espérons que ce sera tout en un pour vous.

Pourquoi manger Toast, quand vous pouvez avoir l'ensemble Snackbar : https://developer.android.com/reference/android/support/design/widget/Snackbar.html

Snackbar> Toast, Toast sur mesure, Crouton

Voici une méthode très simple qui a fonctionné pour moi:

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

La durée de LENGTH_SHORT est de 2 secondes et LENGTH_LONG est de 3,5 secondes, voici le message de pain grillé sera affiché pour 6 secondes , car il est enfermé dans une boucle. Mais un inconvénient de cette méthode est après chaque 2 sec un petit effet de fondu peut se produire. mais il n'y a pas beaucoup perceptible. Espoir, il est utile

L'utilisateur ne peut pas CustomE défini la durée du Toast. parce que la fonction scheduleTimeoutLocked () de NotificationManagerService pas utiliser la durée sur le terrain. le code source est le suivant.

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

Utilisez Crouton, il est une bibliothèque de Toast très flexible.

Crouton

Vous pouvez l'utiliser comme pains grillés:

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

ou vous pouvez même aller un peu plus loin et personnaliser plus, comme le réglage du temps à l'infini! par exemple ici, je veux montrer un message de pain grillé jusqu'à ce que l'utilisateur reconnaît en cliquant dessus.

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

Custome la mise en page qui sera gonflée pour le pain grillé.

<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 toast avec arrière-plan personnalisé et vue a fait l'affaire pour moi. Je l'ai testé en tablette Nexus 7 et j'ai remarqué aucune FADEIN animation fadeout pendant boucle. Heres la mise en œuvre:

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

}

Heres le textview personnalisé utilisé dans le code ci-dessus:

<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 fait mon toast ont coin arrondi comme dans la version KitKat. Vous pouvez ajouter d'autres vues aussi dans le fichier. Toute modification d'amélioration et les commentaires sont encouragés comme je prévois de mettre en œuvre dans mon application en direct.

Planifier un compte à rebours jusqu'à un moment à l'avenir, avec des notifications régulières sur des intervalles le long du chemin. Exemple de montrer un décompte de 30 secondes dans un champ texte:

     new CountDownTimer(30000, 1000) {

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

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


Durée de Toast peut être piraté en utilisant un fil qui court le pain grillé exclusivement. Cela fonctionne (court le pain grillé pendant 10 secondes, modifier sommeil et ctr à votre goût):

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

Ce texte disparaît en 5 secondes.

    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

Edit: Comme Itai Spector dans le commentaire dit qu'il sera montré environ 3,5 secondes, utilisez ce code:

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

Une approche très simple de créer un message un peu plus long est la suivante:

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

Notez que l'exemple ci-dessus élimine l'option LENGTH_SHORT pour garder l'exemple simple.

Vous voulez généralement pas utiliser un message Toast pour afficher les messages pour des intervalles très longs, car ce n'est pas la classe Toast de la destination. Mais il y a des moments où la quantité de texte que vous devez afficher pourrait prendre l'utilisateur plus de 3,5 secondes à lire, et dans ce cas, une légère extension du temps (par exemple, à 6,5 secondes, comme indiqué ci-dessus) peuvent, l'OMI, être utile et conformément à l'usage prévu.

Définit toast à une période donnée en milli-secondes:

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

Après avoir échoué avec toutes les solutions disponibles, j'ai enfin contourner le problème en utilisant récursion.

Code:

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

Non, et la plupart / tous les hacks mentionnés ici ne fonctionnent plus dans Android 9. Mais il y a une solution beaucoup mieux. Si vous message doit traîner, utilisez une boîte de dialogue

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

Une solution très simple à la question. Deux ou trois d'entre eux fera durer plus longtemps Toast. Il est le seul chemin.

Vous pouvez régler l'heure désirée en millisecondes dans la méthode Toast.makeText(); comme ceci:

//40 seconds
long mToastLength = 40*1000 
//this toast will be displayed for 40 seconds.
Toast.makeText(this, "Hello!!!!!", mToastLength).show(); 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top