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

}

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

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

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

相关推荐
雨季6661 小时前
Flutter 三端应用实战:OpenHarmony 简易“动态内边距调节器”交互模式深度解析
javascript·flutter·ui·交互·dart
冠希陈、1 小时前
PHP 判断是否是移动端,更新鸿蒙系统
android·开发语言·php
晚霞的不甘4 小时前
Flutter for OpenHarmony从零到一:构建《冰火人》双人合作闯关游戏
android·flutter·游戏·前端框架·全文检索·交互
2601_949833394 小时前
flutter_for_openharmony口腔护理app实战+饮食记录实现
android·javascript·flutter
独自破碎E4 小时前
【滑动窗口+字符计数数组】LCR_014_字符串的排列
android·java·开发语言
stevenzqzq4 小时前
compose 中 align和Arrangement的区别
android·compose
VincentWei954 小时前
Compose:MutableState 和 mutableStateOf
android
jian110585 小时前
Android studio配置flutter,mac Android studio 发现苹果手机设备
android·flutter·android studio
北极糊的狐5 小时前
光标放在引入的xxx组件行(import { xxx } from ‘element-ui‘;)出现标黄,显示报错:无法解析符号 ‘xxx‘ 解决办法
ui
2501_940007895 小时前
Flutter for OpenHarmony三国杀攻略App实战 - 性能优化与最佳实践
android·flutter·性能优化