Android项目中使用了的Toast,测试过程中发现有部分手机无法正常显示Toast,尝试了数种解决方案后,问题得以解决,以下为封装的工具类,统一的Toast框,也能避免反复弹出不同的Toast框。
public class LKToastUtil { private static Toast mToast; @SuppressLint("StaticFieldLeak") private static TextView tv_toastMsg; private static float bottomHeight = 60; /** * 快速连续弹Toast * * @param msg 需要显示的内容 */ public static void showToastLong(final String msg) { if (msg.equals("")) { return; } LKBaseApplication.getHandler().post(new Runnable() { @Override public void run() { showToast(msg, Toast.LENGTH_LONG); } }); } /** * 快速连续弹Toast * * @param msg 需要显示的内容 */ public static void showToastShort(final String msg) { if (msg.equals("")) { return; } LKBaseApplication.getHandler().post(new Runnable() { @Override public void run() { showToast(msg, Toast.LENGTH_SHORT); } }); } /** * 显示Toast * * @param msg 需要显示的内容 * @param duration 显示时长 */ private static void showToast(final String msg, final int duration) { if (mToast == null) { mToast = new Toast(LKBaseApplication.getApplication()); @SuppressLint("InflateParams") View view = LayoutInflater.from(LKBaseApplication.getApplication()).inflate(R.layout.view_toast, null); tv_toastMsg = view.findViewById(R.id.tv_toastMsg); mToast.setView(view); } tv_toastMsg.setText(msg); mToast.setDuration(duration); mToast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, LKScreenUtil.dp2px(bottomHeight)); mToast.show(); } }
其中LKBaseApplication.getHandler()为Application中定义的全局Handler,如果没有定义的也可以自行传入即可。