我们在程序中经常会有弹出一个toast的需求,而如果每一次都对toast创建出一个新的对象并描述,这样不仅浪费资源而且浪费我们的编码时间。
这是一个工具类,我们需要弹出toast的时候,只要调用XToaster.show方法就能简单地实现toast弹出。
package com.utils.tools;
import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.Toast;
public class XToaster {
private static Toast mToast;
private XToaster() {}
@SuppressLint("ShowToast")
public synchronized static void init(Context ctx) {
if (mToast == null) mToast = Toast.makeText(ctx, "", Toast.LENGTH_LONG);
}
public static void show(final int resId) {
if (mToast == null) throw new NullPointerException("XToaster is not init");
String msg = mToast.getView().getContext().getString(resId);
show(msg);
}
public static void show(final CharSequence msg) {
if (mToast == null) throw new NullPointerException("XToaster is not init");
mToast.setText(msg);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
public static void showPost(final CharSequence msg) {
if (mToast == null) throw new NullPointerException("XToaster is not init");
mToast.getView().post(new XuRunnable(msg));
}
public static void show(final CharSequence msg, int delay) {
if (mToast == null) throw new NullPointerException("XToaster is not init");
mToast.getView().postDelayed(new XuRunnable(msg), delay);
}
private static class XuRunnable implements Runnable {
private CharSequence _msg;
public XuRunnable(CharSequence msg) {
_msg = msg;
}
@Override
public void run() {
// mToast.cancel();
mToast.setText(_msg);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
}
}