android Toast只显示一次
16lz
2022-07-23
Toast在连续弹出显示时,只会显示第一次,后面要显示需要Toast.cancel()
public class ToastUtil { private static Toast mToast; private static Handler mHandler = new Handler(Looper.getMainLooper()); private final static String THREAD_MAIN = "main"; /** * 显示toast(可以子线程中使用Toast)-short * * @param msg Toast消息 */ @SuppressLint("ShowToast") public static void showShortToast(String msg) { try { // 判断是在子线程,还是主线程 if (THREAD_MAIN.equals(Thread.currentThread().getName())) { if (mToast == null) { mToast = Toast.makeText(ContextApp.app(), msg, Toast.LENGTH_SHORT); } else { mToast.cancel(); mToast = Toast.makeText(ContextApp.app(), msg, Toast.LENGTH_SHORT); mToast.setText(msg); } mToast.show(); } else { // 子线程 mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(ContextApp.app(), msg, Toast.LENGTH_SHORT).show(); } }); } } catch (WindowManager.BadTokenException e) { e.printStackTrace(); CrashHandler.postCatchedException(e); //android API25系统BUG,TOAST异常 } } /** * 显示toast(可以子线程中使用Toast)-short * * @param msg Toast消息 */ @SuppressLint("ShowToast") public static void showLongToast(String msg) { try { // 判断是在子线程,还是主线程 if (THREAD_MAIN.equals(Thread.currentThread().getName())) { if (mToast == null) { mToast = Toast.makeText(ContextApp.app(), msg, Toast.LENGTH_LONG); } else { mToast.cancel(); mToast = Toast.makeText(ContextApp.app(), msg, Toast.LENGTH_LONG); mToast.setText(msg); } mToast.show(); } else { // 子线程 mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(ContextApp.app(), msg, Toast.LENGTH_LONG).show(); } }); } } catch (WindowManager.BadTokenException e) { e.printStackTrace(); CrashHandler.postCatchedException(e); //android API25系统BUG,TOAST异常 } }}
更多相关文章
- 浅析Android中的消息机制-解决:Only the original thread that cr
- Android异步消息机制之Handler
- Android的Handler机制详解3_Looper.looper()不会卡死主线程
- Android(安卓)P SystemUI之StatusBar UI布局status_bar.xml解析
- android用户界面-组件Widget-地图视图MapView
- Android之Handler用法总结
- Android中使Dialog显示时背景不变暗
- Android开发之消息处理机制(一)——Handler
- Android异步加载图像小结 (含线程池,缓存方法)