Android Toast工具类 解决Toast不消失 解决非UI线程不能Toast的问题

很简单, 直接上代码:

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());

}

觉得有用,请 点赞 + 关注,您的支持是我最大的动力!

觉得有用,请 点赞 + 关注,您的支持是我最大的动力!

觉得有用,请 点赞 + 关注,您的支持是我最大的动力!

相关推荐
恋猫de小郭5 小时前
Flutter 正在计划提供 Packaged AI Assets 的支持,让你的包/插件可以更好被 AI 理解和选择
android·前端·flutter
钛态7 小时前
Flutter for OpenHarmony 实战:flex_color_scheme 打造极致鸿蒙美学 UI
flutter·ui·harmonyos
AD钙奶-lalala8 小时前
Android编译C++代码步骤详解
android·开发语言·c++
rhett. li9 小时前
FreeBSD系统中使用clang/clang++编译Skia源码的方法
c++·ui·用户界面
特立独行的猫a10 小时前
Kuikly多端框架(KMP)实战:KMP中的 Ktor 网络库的多端适配指南
android·网络·harmonyos·ktor·compose·kmp·kuikly
优选资源分享10 小时前
Seelen UI v2.5.0 丨 Win10/11 桌面定制工具
ui·实用工具
sdff1139611 小时前
【HarmonyOS】Flutter适配鸿蒙多屏异构UI开发实战指南
flutter·ui·harmonyos
滑板上的老砒霜13 小时前
AI 共舞,还是被“注意力刺客”偷袭?——程序员的数字专注力守护指南
android·ai编程·客户端
钛态13 小时前
Flutter for OpenHarmony 实战:Stack Trace — 异步堆栈调试专家
android·flutter·ui·华为·架构·harmonyos
rhett. li13 小时前
Windows系统中使用MinGW-W64(gcc/g++或LLVM)编译Skia源码的方法
c++·windows·ui·用户界面