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

}

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

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

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

相关推荐
奔跑吧 android13 分钟前
【android bluetooth 协议分析 07】【SDP详解 2】【SDP 初始化】
android·bluetooth·aosp15·bt·gd·sdp_init
梦否3 小时前
Android 代码热度统计(概述)
android
xchenhao6 小时前
基于 Flutter 的开源文本 TTS 朗读器(支持 Windows/macOS/Android)
android·windows·flutter·macos·openai·tts·朗读器
coder_pig7 小时前
跟🤡杰哥一起学Flutter (三十五、玩转Flutter滑动机制📱)
android·flutter·harmonyos
消失的旧时光-19438 小时前
OkHttp SSE 完整总结(最终版)
android·okhttp·okhttp sse
ansondroider9 小时前
OpenCV 4.10.0 移植 - Android
android·人工智能·opencv
hsx66611 小时前
Kotlin return@label到底怎么用
android
itgather12 小时前
安卓设备信息查看器 - 源码编译
android
whysqwhw12 小时前
OkHttp之buildSrc模块分析
android
hsx66612 小时前
从源码角度理解Android事件的传递流程
android