Android中Toast消息排列显示工具类

发布于:2025-06-27 ⋅ 阅读:(15) ⋅ 点赞:(0)
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.util.LinkedList;
import java.util.Queue;

public class ToastManager {

    private static ToastManager instance;
    private Queue<String> messageQueue = new LinkedList<>();
    private Toast currentToast;
    private Handler handler = new Handler(Looper.getMainLooper());
    private boolean isShowing = false;

    public static synchronized ToastManager getInstance() {
        if (instance == null) {
            instance = new ToastManager();
        }
        return instance;
    }

    public void showToast(String message) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (messageQueue) {
                    messageQueue.offer(message);
                }
                if (!isShowing) {
                    showNextToast();
                }
            }
        });
    }

    public void clearAllToasts() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (messageQueue) {
                    messageQueue.clear();
                }
                if (currentToast != null) {
                    currentToast.cancel();
                }
            }
        });
    }
    private void showNextToast() {
        final String nextMessage;
        synchronized (messageQueue) {
            nextMessage = messageQueue.poll();
        }
        if (nextMessage != null) {
            isShowing = true;
            currentToast = Toast.makeText(MainApplication.context, nextMessage, Toast.LENGTH_SHORT);
            currentToast.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isShowing = false;
                    showNextToast();
                }
            }, currentToast.getDuration() == Toast.LENGTH_SHORT ? 2000 : 3500); // Adjust duration as needed
        }
    }
}

使用

ToastManager.getInstance().showToast("网络信号不好,稍后再试");
和
ToastManager.getInstance().clearAllToasts()

说明:该工具类支持子线程中使用


网站公告

今日签到

点亮在社区的每一天
去签到