很简单, 直接上代码:
java
package com.wh.view.toast;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
public class ToastUtil {
public static final String TAG = "byWh";
public static final String TAG2 = "ToastUtil - ";
static Toast mToast;
/**
* context 必须是Activity 也就是UI线程
*/
public static void show(Context context, String error) {
if (error.contains("HTTP 429")) {
error = "操作过快,请稍后再试";
}
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(context, error, Toast.LENGTH_LONG);
mToast.show();
}
/**
* context 可以是任何上下文
*/
public static void show2(final Context context, final String error) {
handlerToast.post(new Runnable() {
public void run() {
ToastUtil.show(context, error);
}
});
}
static Handler handlerToast = new Handler(Looper.getMainLooper());
}