Android 弹出 Toast 时取消上一个 Toast(完美方案)增加同步
生活随笔
收集整理的這篇文章主要介紹了
Android 弹出 Toast 时取消上一个 Toast(完美方案)增加同步
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Toast重復(fù)顯示解決方法:
private Toast mToast; public void showToast(String text) { if(mToast == null) { mToast = Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT); } else { mToast.setText(text); mToast.setDuration(Toast.LENGTH_SHORT); } mToast.show(); } public void cancelToast() { if (mToast != null) { mToast.cancel(); } } public void onBackPressed() { cancelToast(); super.onBackPressed(); } 看到Toast有一個(gè)cancel()方法:void cancel() Close the view if it's showing, or don't show it if it isn't showing yet.做程序員的,基本一看api就知道,用這個(gè)可以取消上一個(gè)toast的顯示,然后顯示下一個(gè),這樣就能解決出現(xiàn)的問題??墒窃跍y試的過程中,發(fā)現(xiàn)卻沒有想象中的那么簡單,不信可以百度一下,很多很多人發(fā)現(xiàn)toast的cancel()方法不起作用。還是不講具體過程,只講結(jié)果吧。
創(chuàng)建一個(gè)工具類: import android.content.Context; ? import android.os.Handler; ? import android.os.Looper; ? import android.widget.Toast; public class ToastUtil { private static Handler handler = new Handler(Looper.getMainLooper()); private static Toast toast = null; private static Object synObj = new Object(); public static void showMessage(final Context act, final String msg) { showMessage(act, msg, Toast.LENGTH_SHORT); } public static void showMessage(final Context act, final int msg) { showMessage(act, msg, Toast.LENGTH_SHORT); } public static void showMessage(final Context act, final String msg, final int len) { new Thread(new Runnable() { public void run() { handler.post(new Runnable() { @Override public void run() { synchronized (synObj) { if (toast != null) { toast.cancel(); toast.setText(msg); toast.setDuration(len); } else { toast = Toast.makeText(act, msg, len); } toast.show(); } } }); } }).start(); } public static void showMessage(final Context act, final int msg, final int len) { new Thread(new Runnable() { public void run() { handler.post(new Runnable() { @Override public void run() { synchronized (synObj) { if (toast != null) { toast.cancel(); toast.setText(msg); toast.setDuration(len); } else { toast = Toast.makeText(act, msg, len); } toast.show(); } } }); } }).start(); } }
代碼的邏輯很簡單。這里加了同步,這樣做可以確保每一個(gè)toast的內(nèi)容至少可以顯示出來,而不是還沒顯示就取消掉了。這樣做,是因?yàn)閠oast的內(nèi)容不一定完全相同,如果沒顯示出來,也會有問題。
總結(jié)
以上是生活随笔為你收集整理的Android 弹出 Toast 时取消上一个 Toast(完美方案)增加同步的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 手势解锁 Gesture
- 下一篇: eclipse查看Android应用内存