SoFunction
Updated on 2025-04-09

Android Custom Toast Display Time

Android Custom Toast Display Time

Implementation code:

package ;
import ;
import ;
import ;
import ;
/**
  * Toast custom display time
  *How to use
  * 1. Initialize the class MyToast myToast = new MyToast(this);
  * 2. Display message ("Content to be displayed"); //Set the content to be displayed
  * (8000); //The incoming message display time, unit milliseconds, at least 2000 milliseconds, and can only be multiples of 2000.
  * When 0 is passed, it will be displayed and will only be cancelled when (); is called.
  * 3. Cancel message display ();
  * */
public class ToastUtil {
 private Context mContext = null;
 private Toast mToast = null;
 private Handler mHandler = null;
 private int duration = 0;
 private int currDuration = 0;
 private final int DEFAULT = 2000;
 private Runnable mToastThread = new Runnable() {
  public void run() {
   ();
   (mToastThread, DEFAULT); // Display every 2 seconds   if (duration != 0) {
    if (currDuration <= duration) {
     currDuration += DEFAULT;
    } else {
     cancel();
    }
   }
  }
 }
 public ToastUtil(Context context) {
  mContext = context;
  currDuration = DEFAULT;
  mHandler = new Handler(());
  mToast = (mContext, "", Toast.LENGTH_LONG);
 }
 public void setText(String text) {
  (text);
 }
 public void show(int duration) {
   = duration;
  (mToastThread);
 }
 public void setGravity(int gravity, int xOffset, int yOffset) {
  (gravity, xOffset, yOffset);
 }
 public void setDuration(int duration) {
  (duration);
 }
 public void setView(View view) {
  (view);
 }
 public void cancel( ) {
  (mToastThread);// Delete the display thread first  ();// Cancel the display effect of the last thread and it will be completely over  currDuration = DEFAULT;
 }
}


Thank you for reading, I hope it can help you. Thank you for your support for this site!