Android ToastUtil

2930 ワード


import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;

/**
 * author cowards
 * created on 2018\12\21 0021
 **/
public class ToastUtil {

    private static Toast toast;//           Toast  ,       Toast     

    /**
     *      Toast【  】
     *
     * @param msg      -   
     */
    public static void showShortToast(Context context, String msg) {
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        //1、setGravity        ,     toast                (           ,      setGravity   ,    )
        //2、          ,  ,              ,      ,      :
        toast.setGravity(Gravity.BOTTOM, 0, dip2px(context, 64));
        toast.show();
    }

    /**
     *      Toast【  】
     *
     * @param msg      -   
     */
    public static void showShortToastCenter(Context context, String msg) {
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     *      Toast【  】
     *
     * @param msg      -   
     */
    public static void showShortToastTop(Context context, String msg) {
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    /**
     *      Toast【  】
     *
     * @param msg      -   
     */
    public static void showLongToast(Context context, String msg) {
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        } else {
            toast.setText(msg);
        }
        toast.setGravity(Gravity.BOTTOM, 0, dip2px(context, 64));
        toast.show();
    }

    /**
     *      Toast【  】
     *
     * @param msg      -   
     */
    public static void showLongToastCenter(Context context, String msg) {
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        } else {
            toast.setText(msg);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     *      Toast【  】
     *
     * @param msg      -   
     */
    public static void showLongToastTop(Context context, String msg) {
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        } else {
            toast.setText(msg);
        }
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}