Android原生的Toast虽说不复杂, 但也不是很方便, 如果需要更换Toast的背景, 则需要写不少重复代码. 本着遵循DRY的原则, 理当将Toast封装一下:
public class ToastMgr {
private static Toast it;
private ToastMgr() {
}
/**
* 在程序初始化的时候调用, 只需调用一次
*/
public static void init(Context _context) {
View v = Toast.makeText(_context, "", Toast.LENGTH_SHORT).getView();
init(_context, v);
}
/**
* 在程序初始化的时候调用, 只需调用一次
*/
public static void init(Context _context, View view) {
it = new Toast(_context);
it.setView(view);
}
/**
* 设置Toast背景
*/
public static void setBackgroundView(View view) {
checkInit();
it.setView(view);
}
public static void show(CharSequence text, int duration) {
checkInit();
it.setText(text);
it.setDuration(duration);
it.show();
}
public static void show(int resid, int duration) {
checkInit();
it.setText(resid);
it.setDuration(duration);
it.show();
}
public static void show(CharSequence text) {
show(text, Toast.LENGTH_SHORT);
}
public static void show(int resId) {
show(resId, Toast.LENGTH_SHORT);
}
private static void checkInit() {
if (it == null) {
throw new IllegalStateException("ToastMgr is not initialized, please call init once before you call this method");
}
}
}
ToastMgr.init(getApplicationContext());
通过ToastMgr产生的Toast与系统自带的Toast有一个最大的区别就是, 不论前面有多少Toast, 都会被最后一个Toast覆盖, 然后2秒后消失. 原生自带的则是一个接一个的显示. 因为ToastMgr中的是Toast单例, 而原生的不是.