步骤一:新建ToastUtil类
public class ToastUtil {
private static ToastUtilmToastUtil;
private ContextmContext;
private ToastmToast;
public static ToastUtil init(Context context) {
if (mToastUtil ==null) {
mToastUtil =new ToastUtil(context);
}
return mToastUtil;
}
public static ToastUtil getInstance() {
if (mToastUtil ==null) {
throw new NullPointerException("请在Application中初始化ToastUtil");
}
return mToastUtil;
}
private ToastUtil(Context context) {
mContext = context;
init();
}
/**
* toast string消息,时间2秒
*
* @param msg
*/
public void showToast(String msg) {
mToast.setText(msg);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
/**
* toast string消息,时间2秒
*
* @param msg
*/
public void showToast(String msg,int time) {
mToast.setText(msg);
mToast.setDuration(time);
mToast.show();
}
/**
* toast string消息,时间2秒
*
* @param resId
*/
public void showToast(int resId) {
mToast.setText(mContext.getResources().getString(resId));
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
private void init() {
LogUtil.e("ToastUtil","初始化ToastUtil");
mToast = Toast.makeText(mContext,"", Toast.LENGTH_SHORT);
}
}
步骤二:在Application类的onCreate()方法里调用
ToastUtil.init(getApplicationContext());