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弱引用