一個簡單的Toast實用工具類!

openkk 12年前發布 | 6K 次閱讀 LoopBack

不管是為了統一風格還是為了使用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" />

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!