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

}

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

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

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

相关推荐
2501_9371931432 分钟前
技术加持!PLB-TV:HDR10+UDP 传输
android·源码·源代码管理·机顶盒
霸王大陆3 小时前
《零基础学 PHP:从入门到实战》模块十:从应用到精通——掌握PHP进阶技术与现代化开发实战-2
android·开发语言·php
松☆4 小时前
OpenHarmony + Flutter 混合开发高阶:实现无障碍(Accessibility)与适老化 UI 的深度集成
flutter·ui
低调小一6 小时前
在 Android 上获取视频流逐帧时间戳并与 GPS/IMU 对齐(CameraX 实践)
android
Android_Trot7 小时前
Flutter android 多渠道配置,多包名、icon、等配置。
android·flutter
zhangphil8 小时前
Android性能:trace上的锁竞争monitor contention with owner at
android
砖厂小工8 小时前
Now In Android 精讲 9 - Benchmark 与 Baseline Profile
android
愤怒的代码9 小时前
深入解析 SystemUI 依赖注入:Dagger2 与 Hilt 核心机制重温
android·dagger
從南走到北10 小时前
JAVA海外短剧国际版源码支持H5+Android+IOS
android·java·ios