Toast helper class for Android

Toast is often used in some projects, as well as things like Log, which are simple and very commonly used.

Then repackage it

/**
 * Author: CoolTone
 * Description: ToastUtils toast helper class
 * Time: 2018/4/24
 */
public class ToastUtils {
    private static Toast toast;

    private ToastUtils() {
    }

    /**
     * Short Toasts that don't show up all the time
     *
     * @param context
     * @param content
     */
    public static void showToastShort(Context context, String content) {
        if (toast == null) {
            toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);  // 位置
        toast.setText(content);
        toast.show();
    }

    /**
     * Long Toast that doesn't always show
     *
     * @param context
     * @param content
     */
    public static void showToastLong(Context context, String content) {
        if (toast == null) {
            toast = Toast.makeText(context, content, Toast.LENGTH_LONG);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);  // 位置
        toast.setText(content); // text  
        toast.show(); // show
    }

    /**
     * Toast with custom layout
     *
     * @param context
     * @param layout
     */
    public static void showToastLong(Context context, int layout) {
        View view = LayoutInflater.from(context).inflate(layout, null);
        if (toast == null) {
            toast = new Toast(context);
        }
        toast.setView(view);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * Toast with custom layout
     *
     * @param context
     * @param layout
     */
    public static void showToastShort(Context context, int layout) {
        View view = LayoutInflater.from(context).inflate(layout, null);
        if (toast == null) {
            toast = new Toast(context);
        }
        toast.setView(view);                    // view
        toast.setDuration(Toast.LENGTH_SHORT); // display time  
        toast.setGravity(Gravity.CENTER, 0, 0); // display position
        toast.show(); // show
    }
}


This Toast helper class reduces toast overlays, adds custom layouts, and of course you can listen to layout events, depending on how you modify it!






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324776802&siteId=291194637