开发中经常会用到Toast显示一些提示信息,但是每次都构造一个Toast很麻烦,所以写一个Toast工具类,方便开发;
优点:
1.不用每次构造Toast(传入3个参数),用工具后只需传入一个参数,方便开发;
2.这个Toast为单例,防止同一时间创建多个toast,长时间显示;
3.自动判断显示时间(大于12个字符,长时间显示)。
代码如下:
/**
* Created by Administrator on 2016/12/28.
*/
public class ToastUtil {
//单例模式
private static Toast toast;
public static void toast(String str) {
//判断是否为空
if (TextUtils.isEmpty(str))
return;
//根据字符串长度设置显示时间
if (str.length() > 12) {
//懒加载
if (toast == null)
//其中MyApplication为自定义的Application,需要在其中定义getContext方法,返回getApplicationContext()
toast = Toast.makeText(MyApplication.getContext(), str, Toast.LENGTH_LONG);
else {
toast.setDuration(Toast.LENGTH_LONG);
toast.setText(str);
}
} else {
if (toast == null)
toast = Toast.makeText(MyApplication.getContext(), str, Toast.LENGTH_SHORT);
else {
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(str);
}
}
toast.show();
}
}