对应的一个工具类
public class ToastUtils {
private static Toast sToast;
private static Handler handler = new Handler(Looper.getMainLooper());
public static void showToast(final Context context, final String msg) {
if (sToast == null) {
if (Looper.getMainLooper()==Looper.myLooper()){
initToast(context, msg);
}else {
handler.post(new Runnable() {
@Override
public void run() {
initToast(context, msg);
}
});
}
}
//判断当前代码是否是主线程
if (Looper.myLooper() == Looper.getMainLooper()) {
sToast.setText(msg);
sToast.show();
} else {
handler.post(new Runnable() {
@Override
public void run() {
sToast.setText(msg);
sToast.show();
}
});
}
}
private static void initToast(Context context, String msg) {
sToast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT);
sToast.setText(msg);
}
}
接下来 就是自己在封装的基类 或者activity里面调用 道理都一样
//对应一个点击事件toast一下
tv_apply_selled_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showMsg("格式错误");
}
});
下面的方法是自己定义的方法 里面对应的msg 就是toast的内容
public void showMsg(String msg) {
ToastUtils.showToast(ApplyjyActivity.this,msg);
}
showMSG
第二种简单
public class ToastUtils {
private static Toast mToast;
public static void showShort(Context context, String text) {
// if (mToast == null) {
// mToast =
//
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
// } else {
// mToast.setText(text);
// mToast.setDuration(Toast.LENGTH_SHORT);
// }
// mToast.show();
}
public static void showShort(Context context, int text) {
if (mToast == null) {
mToast = Toast.makeText(context, text + "", Toast.LENGTH_SHORT);
} else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
}
mToast.show();
}
public static void showLong(Context context, String text) {
if (mToast == null) {
mToast = Toast.makeText(context, text, Toast.LENGTH_LONG);
} else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_LONG);
}
mToast.show();
}
public static void showLong(Context context, int text) {
if (mToast == null) {
mToast = Toast.makeText(context, text + "", Toast.LENGTH_LONG);
} else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_LONG);
}
mToast.show();
}
// toast重复显示不消失问题
public static void toastShow(Context context, String arg) {
if (mToast == null) {
mToast = Toast.makeText(context, arg, Toast.LENGTH_SHORT);
} else {
// toast.cancel(); //取消后只会显示一次
mToast.setText(arg);
}
mToast.show();
}
}
下面是咋调用
ToastUtils.showShort(this, "请先登录");