Toast类避免显示时间叠加的方法(线程中可用)

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.widget.Toast;

/**
 * Toast工具类
 * Created by user on 2016/12/22.
 */

public class ToastUtil {

    private static Toast toast = null;
    private static ToastUtil toastUtil = null;

    public ToastUtil(){}

    public synchronized static ToastUtil getInstance(){
        if(null == toastUtil){
            toastUtil = new ToastUtil();
        }

        return toastUtil;
    }

    public void showToast(Context context, String string){

        if(toast != null){
            toast.cancel();
        }
            toast = Toast.makeText(context, string,Toast.LENGTH_SHORT);
            toast.show();
    }

    public void showToast(Fragment fragment, String string){
        showToast(fragment.getActivity(),string);
    }

    public void showToast(Activity activity, String string){
        if(toast != null){
            toast.cancel();
        }
        toast = Toast.makeText(activity, string,Toast.LENGTH_SHORT);
        toast.show();
    }

    public void showToastTest(Context context){
        if(toast != null){
            toast.cancel();
        }
        toast = Toast.makeText(context, "click",Toast.LENGTH_SHORT);
        toast.show();
    }

    public void showToastTest(Fragment fragment){
        showToastTest(fragment.getActivity());
    }

    public void showToastTest(Activity activity){
        if(toast != null){
            toast.cancel();
        }
        toast = Toast.makeText(activity, "click",Toast.LENGTH_SHORT);
        toast.show();
    }
}

        if(null == toastUtil){
            toastUtil = new ToastUtil();
        }

        return toastUtil;
    }
public void showToastInThread(Context context,String msg){
        Looper.prepare();
        if(toast != null){
            toast.cancel();
        }
        toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.show();
        Looper.loop();
    }
    public void showToast(Context context, String string){

        if(toast != null){
            toast.cancel();
        }
            toast = Toast.makeText(context, string,Toast.LENGTH_SHORT);
            toast.show();
    }

}

这是一个封装好的Toast工具类,避免时间叠加

使用方法

ToastUtil.getInstance().showToast(mContext,"test");
如果在线程中执行的话,必须按照如下格式


ToastUtil.getInstance().showToastInThread(mContext,"str");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值