Java tutorial
//package com.java2s; //License from project: Apache License import android.content.Context; import android.os.Handler; public class Main { public static final long DEFAULT_DURATION = 1000L; public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG; public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT; private static android.widget.Toast normalToast; private static android.widget.Toast gravityToast; private static Handler handler; private static Runnable run = new Runnable() { public void run() { if (normalToast != null) normalToast.cancel(); if (gravityToast != null) gravityToast.cancel(); } }; private static void toast(Context context, CharSequence text, int duration) { if (context == null) return; handler.removeCallbacks(run); long delayMillis; switch (duration) { case LENGTH_LONG: delayMillis = 3000L; break; case LENGTH_SHORT: default: delayMillis = DEFAULT_DURATION; break; } if (normalToast == null) { normalToast = android.widget.Toast.makeText(context, text, duration); } else { normalToast.setText(text); } handler.postDelayed(run, delayMillis); normalToast.show(); } private static void toast(Context context, CharSequence text, int duration, int gravity, int xOffset, int yOffset) { if (context == null) return; handler.removeCallbacks(run); long delayMillis; switch (duration) { case LENGTH_LONG: delayMillis = 3000L; break; case LENGTH_SHORT: default: delayMillis = DEFAULT_DURATION; break; } if (gravityToast == null) { gravityToast = android.widget.Toast.makeText(context, text, duration); } else { gravityToast.setText(text); } gravityToast.setGravity(gravity, xOffset, yOffset); handler.postDelayed(run, delayMillis); gravityToast.show(); } public static void show(Context context, CharSequence text, int duration) { if (duration > 0) { duration = LENGTH_SHORT; } toast(context, text, duration); } public static void show(Context context, int resId, int duration) throws NullPointerException { if (null == context) throw new NullPointerException("The context is null!"); duration = duration > 0 ? LENGTH_LONG : LENGTH_SHORT; toast(context, context.getResources().getString(resId), duration); } }