Android Toast 部分手机无法显示问题(如小米手机)解决

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,如果没有定义的也可以自行传入即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值