自定义Toast工具类

匿名 (未验证) 提交于 2019-12-02 23:26:52

自己封装的Toast,在子线程中可以显示,现在Toast正在被Snackbar逐步替代,使用Toast的人越来越少,但在开发过程或调试过程中,Toast的用处还是挺大的。自己封装,便于查找和记录,不喜勿喷~~~~

原理是创建拥有主线程Looper的Handler,在该Handler中进行显示Toast的操作,这样在子线程中也可以进行显示Toast,代码如下:

 public class ToastUtils {     private static Toast toast;     private static Handler handler = new Handler(Looper.getMainLooper());      private ToastUtils() {}      public static void showShortToast(final String msg) {         handler.post(()-> showToast(msg,Toast.LENGTH_SHORT));     }      public static void showLongToast(String msg) {         handler.post(()-> showToast(msg,Toast.LENGTH_LONG));     }      private static void showToast(CharSequence text, int duration) {         if (toast == null) {             toast = Toast.makeText(App.getApp(), text, duration);             TextView tv = toast.getView().findViewById(android.R.id.message);             tv.setTextSize(16);             toast.setGravity(Gravity.CENTER,0,0);         }else {             toast.setText(text);             toast.setDuration(duration);         }         toast.show();     } }

自己封装,便于使用。

文章来源: https://blog.csdn.net/Dream_201603/article/details/88842861
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!