Android 简单的ToastUtil(位置,布局,时长)

复制以下文件可直接使用:
public class ToastUtil {
    /**
     * show short toast
     *
     * @param msg
     */
    public static void showShortToast(String msg) {
        Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * show long toast
     *
     * @param msg
     */
    public static void showLongToast(String msg) {
        Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG).show();
    }

    /**
     * 居中显示 short toast
     *
     * @param msg
     */
    public static void showCenterShortToast(String msg) {
        Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }


    /**
     * 居中显示 long toast
     *
     * @param msg
     */
    public static void showCenterLongToast(String msg) {
        Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG);

        //Gravity.CENTER  Gravity.LEFT Gravity.RIGHT Gravity.TOP
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 自定义toast布局,并居中显示
     *
     * @param msg
     */
    public static void showCustomShortToast(String msg) {
        View view = LayoutInflater.from(MyApplication.getInstance()).inflate(R.layout.toast_layout, null);
        TextView textView = view.findViewById(R.id.id_content);
        textView.setText(msg);
        Toast toast = new Toast(MyApplication.getInstance());
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setView(view);
        toast.show();
    }

    /**
     * 自定义toast 显示的时长
     *
     * @param msg
     */
    public static void showCustomTimeShortToast(String msg, int time) {

        final Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG);
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3500);//0秒后执行,LENGTH_LONG时间为3.5s,所以设置3500毫秒后再次执行

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, time);//time时间后执行取消taost,取消timer.
    }
}
ToastUtil文件中使用到的MyApplication文件如下:
public class MyApplication extends Application {

    public static MyApplication instance;

    public static MyApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}

自定义Toast布局文件如下:



    
        

        
    



效果如下:
(录屏工具推荐:GifCam 下载地址:http://www.bahraniapps.com/apps/gifcam/gifcam.php)

你可能感兴趣的:(Android 简单的ToastUtil(位置,布局,时长))