(安卓)Toast消息队列输出

我怕爱的太早我们不能终老 提交于 2020-01-14 02:07:06

package sc.tool;

import java.util.ArrayList;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;


/** 示例:ToastQueue.ShowToastQueue(this, "Toast消息队列逐个输出");
 * 
 * ToastQueue.java: Toast消息队列输出,Android 9.0 版本后Toast消息连续输出,后出现的Toast会替换掉之前的Toast消息,使得Toast展示不全(同一时间,仅展示最后一条);
 * 此类用于实现Toast消息的队列输出,按调用顺序,逐个展示,不覆盖、不丢失。
 * 
 * ----- 2020-1-10 下午2:56:44 scimence */
public class ToastQueue
{
	// 示例:ToastQueue.ShowToastQueue(this, "");
	// Toast.makeText(activity, info, Toast.LENGTH_SHORT).show();
	// ShowToastQueue(activity.getApplicationContext(), info);
	
	// ---------------------
	// Toast消息队列输出逻辑
	
	public static void ShowToastQueue(final Context context, String info)
	{
		synchronized (ToastList)
		{
			ToastList.add(info);
			if (!ToastQueueisShowing) ShowToastQueueProcess(context.getApplicationContext());
		}
	}
	
	/** 获取主线程Handler */
	private static Handler getMainHandler()
	{
		return new Handler(Looper.getMainLooper());
	}
	
	private static boolean ToastQueueisShowing = false;
	private static ArrayList<String> ToastList = new ArrayList<String>();
	
	private static Context ToastQueueContext = null;
	
	public static void ShowToastQueueProcess(final Context context)
	{
		synchronized (ToastList)
		{
			if (ToastList != null && ToastList.size() > 0)
			{
				ToastQueueisShowing = true;
				if (ToastQueueContext == null) ToastQueueContext = context;
				
				final String info = ToastList.get(0);
				ToastList.remove(0);
				
				getMainHandler().post(new Runnable()
				{
					@Override
					public void run()
					{
						Toast.makeText(ToastQueueContext, info, Toast.LENGTH_SHORT).show();
					}
				});
				
				getMainHandler().postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						ShowToastQueueProcess(context);
					}
				}, 2500);
			}
			else ToastQueueisShowing = false;
		}
	}

	// ---------------------
	
}


 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!