Toast

1.在application中获取 context 的标准写法

 public static Context mContext;
 public static TextApplication getApplication() {
        if (mContext == null) {
            synchronized (TextApplication.class) {
                if (mContext == null) {
                    mContext = new TextApplication();
                }
            }
        }
        return mContext;
    }

2.Toast在代码中要多次用 可能会写成

 public Toast toast = null;

//显示的时候

 toast = Toast.makeText(mContext, R.string.test, Toast.LENGTH_LONG);
 toast.show();

这样的写法在第一次调用的时候会报错

 因为toast = null  再makeText时相当于 Lopper = null 是不会创建任何Toast的,所以仍然是null,show的时候就会报错。

再次调用又没有错的原因是

toast.show的时候会创建这个对象,所以后面就不会报错了。

所以上面的写法有错

下面一个Toast的的util类

public class ToastUtil {
    private static WeakReference<Toast>rfToast;

    public static void show(Context context,String msg,int duration) {
        cancel();
        Toast toast;
        try {
            toast = Toast.makeText(context,msg,duration);
            toast.show();
        } catch (Exception e) {
            e.printStackTrace();
//解决子线程显示toast报错的问题
            Looper.prepare();
            toast = Toast.makeText(context,msg,duration);
            toast.show();
            Looper.loop();
        }
        rfToast = new WeakReference<>(toast);
    }
    
    public static void cancel() {
        if (rfToast != null && rfToast.get() != null) {
            rfToast.get().cancel();
            rfToast = null;
        }
    }
}
//感觉这里的弱引用没有意义 都不如context弱引用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值