自己封装的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