Android Custom Shortening Toast Display Time Instance Code

  • 2021-11-14 07:00:38
  • OfStack

My main purpose is to shorten the display time of Toast. If you want to extend the time, you can change it yourself

Don't talk too much, see the code


import android.content.Context;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
public class ToastUtil {
  private String TAG = "ToastUtil";
  private Toast mToast;
  private TimeCount timeCount;
  private String message;
  private boolean canceled = true;
  public ToastUtil(Context context, String msg) {
    message = msg;
    Log.i("ToastUtil", "Toast start...");
    if (mToast == null) {
      mToast =Toast.makeText(context,message,Toast.LENGTH_SHORT); 
      Log.i("ToastUtil", "Toast create...");
    }
  }
  /**
   *  Custom centered display toast
   */
  public void show() {
    mToast.show();
    Log.i("ToastUtil", "Toast show...");
  }
  /**
   *  Custom duration, displayed in the center toast
   * @param duration
   */
  public void show(int duration) {
    timeCount = new TimeCount(duration, 100);
    Log.i("ToastUtil", "Toast show...");
    if (canceled) {
      timeCount.start();
      show();
      canceled = false;
    }
  }
  /**
   *  Hide toast
   */
  private void hide() {
    if (mToast != null) {
      mToast.cancel();
    }
    canceled = true;
    Log.i("ToastUtil", "Toast that customed duration hide...");
  }
  /**
   *  Custom timer 
   */
  private class TimeCount extends CountDownTimer {
    public TimeCount(long millisInFuture, long countDownInterval) {
      super(millisInFuture, countDownInterval); //millisInFuture Total duration, countDownInterval Time interval (1 Be general 1000ms)
    }
    @Override
    public void onTick(long millisUntilFinished) {
      Log.e(TAG, ": " + millisUntilFinished / 100 + " Post-disappearance " );
    }
    @Override
    public void onFinish() {
      hide();// Cancel after counting Toast Display of 
    }
  }
}

Usage:


ToastUtil toastUtil = new ToastUtil(MainActivity.this," Save successfully !");//MainActivity.this For 
//Context,

toastUtil.show(500);

Summarize

Above is this site to introduce Android custom shorten Toast display time example code, I hope to help you!


Related articles: