Android自定義Toast,多次彈出時取消上次彈出,最后一次彈出為準
Android的Toast用隊列管理彈出的消息,這個自定義的Toast用于頻繁彈出Toast時取消之前的toast,只顯示最后一個Toast,前后文字長度相差較大時,兩個Toast提示的切換不太理想,大神們有啥建議還望不吝賜教。
public abstract class Toast { public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT; public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;private static android.widget.Toast toast; private static Handler handler = new Handler(); private static Runnable run = new Runnable() { public void run() { toast.cancel(); } }; private static void toast(Context ctx, CharSequence msg, int duration) { handler.removeCallbacks(run); // handler的duration不能直接對應Toast的常量時長,在此針對Toast的常量相應定義時長 switch (duration) { case LENGTH_SHORT:// Toast.LENGTH_SHORT值為0,對應的持續時間大概為1s duration = 1000; break; case LENGTH_LONG:// Toast.LENGTH_LONG值為1,對應的持續時間大概為3s duration = 3000; break; default: break; } if (null != toast) { toast.setText(msg); } else { toast = android.widget.Toast.makeText(ctx, msg, duration); } handler.postDelayed(run, duration); toast.show(); } /** * 彈出Toast * * @param ctx * 彈出Toast的上下文 * @param msg * 彈出Toast的內容 * @param duration * 彈出Toast的持續時間 */ public static void show(Context ctx, CharSequence msg, int duration) throws NullPointerException { if (null == ctx) { throw new NullPointerException("The ctx is null!"); } if (0 > duration) { duration = LENGTH_SHORT; } toast(ctx, msg, duration); } /** * 彈出Toast * * @param ctx * 彈出Toast的上下文 * @param msg * 彈出Toast的內容的資源ID * @param duration * 彈出Toast的持續時間 */ public static void show(Context ctx, int resId, int duration) throws NullPointerException { if (null == ctx) { throw new NullPointerException("The ctx is null!"); } if (0 > duration) { duration = LENGTH_SHORT; } toast(ctx, ctx.getResources().getString(resId), duration); }
}
</pre>
本文由用戶 efbb 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!