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

}

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

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

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

相关推荐
海雅达手持终端PDA15 分钟前
工业手持终端的“去手机化”演进:看海雅达如何以“同轴扫摄”终结工程妥协,重塑工业PDA新范式
android·物联网·智能手机·硬件工程·能源·制造·iot
booboosui1 小时前
删掉一个住在本机的 agent:8 处要清,顺序不能反
android
hcgeng2 小时前
Android获取崩溃日志
android
aqi002 小时前
AI编程让鸿蒙开发电子书APP更加快捷
android·华为·harmonyos·鸿蒙·harmony
GY-932 小时前
【Android】Android Studio 中的协程
android
Geek-Chow2 小时前
移动 App 侧载攻击:Android 与 iOS 的信任链、突破口与防护
android
Android小码家3 小时前
framework&framework-minus-apex&android.jar的区别
android·python·jar
技术风向解码者3 小时前
安卓跨端选型:为什么优先看 Kuikly
android
科小怪3 小时前
大肥鱼桌宠下载(2026最新版):在安卓桌面上养一条会走会弹会碎碎念的胖鱼
android