一个简单的Toast实用工具类!

12年前

不管是为了统一风格还是为了使用Toast更好看,或者使用Toast更方便,自己经过几番改进,写出了

下面的Toast实用工具类,与大家分享.请大家指教:

1.方法经过了多次重构,应该没有什么多余的代码.这要多感谢曾经给过多帮助的重构一书.

2.有使用自定义布局的示例.

3.代码显而易见,所以就没有多余的注释了.

 

先上代码:

public class ToastUtils {     private static int GRAVITY = Gravity.CENTER;     public static void showLong(Context context, String message) {    show(context, message, Toast.LENGTH_LONG);   }     public static void showShort(Context context, String message) {    show(context, message, Toast.LENGTH_SHORT);   }     public static void showLong(Context context, int textId) {    show(context, textId, Toast.LENGTH_LONG);   }     public static void showShort(Context context, int textId) {    show(context, textId, Toast.LENGTH_SHORT);   }     public static void show(Context context, String text, int duration) {    Toast toast = Toast.makeText(context, text, duration);    toast.setGravity(GRAVITY, 80, 80);    toast.show();   }     public static void show(Context context, int textId, int duration) {    Toast toast = Toast.makeText(context, textId, duration);    toast.setGravity(GRAVITY, 80, 80);    toast.show();   }     public static void showSuccess(Context context, int textId) {    showIconToast(context, textId, R.drawable.ic_success, R.color.holo_blue);   }     public static void showFailure(Context context, int textId) {    showIconToast(context, textId, R.drawable.ic_failure, R.color.warn);   }     public static void showIconToast(Context context, int textId, int iconId,     int colorId) {    LayoutInflater inflater = (LayoutInflater) context      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);    View layout = inflater.inflate(R.layout.toast, null);    ((TextView) layout).setText(textId);    ((TextView) layout).setTextColor(context.getResources().getColor(      colorId));    ((TextView) layout).setCompoundDrawablesWithIntrinsicBounds(iconId, 0,      0, 0);    Toast toast = new Toast(context);    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);    toast.setDuration(Toast.LENGTH_SHORT);    toast.setView(layout);    toast.show();   }    }

再上自定义Toast的布局文件:R.layout.toast

<?xml version="1.0" encoding="utf-8"?>  <TextView xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:background="@drawable/toast_bg"      android:drawablePadding="20dp"      android:gravity="center"      android:padding="20dp"      android:text="success"      android:textSize="16sp"      android:textStyle="bold" />