Android工具类之 toast

/**
     * //带图片的吐司窗体
     *
     * @param context 上下文
     * @param message 吐司内容
     * @param imageId 图片ID
     */
    public static void ToastWithImage(final Context context, final Object message, int imageId) {
        Toast toast = Toast.makeText(context.getApplicationContext(), "" + message, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        LinearLayout toastView = (LinearLayout) toast.getView();
        if (imageId != 0) {
            ImageView imageCodeProject = new ImageView(context.getApplicationContext());
            imageCodeProject.setImageResource(imageId);
            toastView.addView(imageCodeProject, 0);
            toast.show();
        }
        if (imageId == 0) {
            toast.show();
        }
    }


    /**
     * 快速快速toast  让其在主线程进行
     *
     * @param mContext
     * @param msg
     */
    public static void showToast(final Context mContext, final String msg) {
        try {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                //说明是在主线程
                safeToast(mContext, msg);
            } else {
                //说明不是在主线程
                if (handler == null) {
                    handler = new Handler(Looper.getMainLooper());
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        safeToast(mContext, msg);
//                        toast(mContext, msg);
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 安全的toast 避免内存溢出
     *
     * @param mContext
     * @param msg
     */
    private static void safeToast(Context mContext, String msg) {
        try {
            if (mToast == null || mToast.get() == null) {
                mToast = new SoftReference(Toast.makeText(mContext, msg, Toast.LENGTH_SHORT));
            }
            mToast.get().setText("" + msg);
            mToast.get().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param mContext
     * @param msg
     */
    private static void toast(Context mContext, String msg) {
        if (toast == null) {
            toast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
        }
        toast.setText(msg);
        toast.show();
    }

你可能感兴趣的:(Android工具类之 toast)