一、编写一个Toast工具类
public class ToastUtils {
private static Toasttoast =null;
public static boolean isShow =true;
private static void showMessageTwo(Context context, CharSequence message, boolean showicon) {
cancelCurrentToast();
if(toast ==null){
toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);//创建Toast对象
LinearLayout toastView = (LinearLayout)LayoutInflater.from(context).inflate(R.layout.toast_view, null);//获取自定义布局
TextView tv = toastView.findViewById(R.id.tv_toast);
ImageView iv_toast =toastView.findViewById(R.id.iv_toast);
tv.setText(message);
iv_toast.setVisibility(mShowicon ? View.VISIBLE : View.GONE);//设置图标是否显示
toast.setGravity(Gravity.LEFT, 200, 200);//设置显示的位置
toast.setView(toastView);
}else {
TextView tv =toast.getView().findViewById(R.id.tv_toast);
tv.setText(message);
}
toast.show();
}
//在需要吐司的地方调此方法进行显示
public static void showTwo(Context context,CharSequence message, boolean showicon) {
if(isShow && context !=null){
showMessageTwo(context,message, showicon);
}
}
//先关闭当前显示的Toast
public static void cancelCurrentToast() {
if (toast !=null) {
toast.cancel();
toast =null;
}
}
}
二、自定义的布局,布局根据需要自己定义