public class ToastUtils { private Toast mToast = null; private Context mContext; private static volatile ToastUtils instance; private ToastHandler toastHandler; private final int SHOW_TOAST=0; private ToastUtils(Context context){ this.mContext=context; toastHandler=new ToastHandler(); } public static ToastUtils getInstance(Context context) { if (instance == null){ synchronized (ToastUtils.class){ if (instance == null){ instance = new ToastUtils(context); } } } return instance; } private void show(String str) { if (mToast == null) {// 防止多个toast重复显示 mToast = Toast.makeText(mContext, str, Toast.LENGTH_SHORT); } else { mToast.setText(str); } mToast.show(); } public void showToast(String str){ Message msg=new Message(); Bundle b=new Bundle(); b.putString("str",str); msg.setData(b); toastHandler.sendMessage(msg); } private class ToastHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle b=msg.getData(); switch (msg.what){ case SHOW_TOAST: show(b.getString("str")); break; default: break; } } } private void log(String str) { android.util.Log.i("chenxi", str + " @"+getClass().getSimpleName()); } }
将Toast.Show()放在Handler中可以避免频繁显示toast显示时出现的异常