自己用来显示Toast的

<span style="font-family: Arial, Helvetica, sans-serif;"></pre><pre name="code" class="java"></span>
android 的toast不能长时间显示,纠结了半天,搞了这么一个东东,以后显示toast就用你了...
</pre><pre name="code" class="java">import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

/**
 * 显示Toast
 */
public class MyToast {
	private static Toast mToast;
	/**
	 * 延时线程
	 */
	private static DelayThread delay;
	/**
	 * 是否正在长显示
	 */
	public static boolean isShow = false;
	private static String tempStr = null;
	private static Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0x00:// 持续显示用
				if (!isShow) {
					break;
				}
				if (tempStr != null && mToast != null) {
					mToast.setText(tempStr);
					mToast.setDuration(Toast.LENGTH_LONG);
					mToast.show();
					break;
				}
			case 0x01:// 取消用
				System.out.println("-->>cancle");
				isShow = false;
				if (delay != null) {
					delay.interrupt();
				}
				// mToast=null;
				tempStr = null;
				delay = null;
				break;

			default:
				break;
			}
		};
	};

	/**
	 * 显示吐司
	 * 
	 * @param str
	 */
	public static void showToast(Context context, String str) {
		if (isShow)
			cancel();
		if (mToast == null) {
			mToast = Toast.makeText(context, str, Toast.LENGTH_LONG);
		} else {
			mToast.setText(str);
			mToast.setDuration(Toast.LENGTH_LONG);
		}
		mToast.show();
	}

	/**
	 * 取消吐司
	 */
	public static void cancel() {
		// isShow = false;
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		if (isShow) {
			handler.sendEmptyMessage(0x01);
		}
	}

	/**
	 * 一直显示直到取消的吐司或者显示了其他吐司
	 * 
	 * @param str
	 */
	public static void showToastUntillCancle(Context context, String str) {
		isShow = true;
		tempStr = str;
		if (mToast == null) {
			mToast = Toast.makeText(context, tempStr, Toast.LENGTH_LONG);
			mToast.show();
		}
		if (delay == null) {
			delay = new DelayThread();
			delay.start();
		}
	}

	/**
	 * 延时线程,每3s判断一次
	 * 
	 * @author Administrator
	 *
	 */
	static class DelayThread extends Thread {
		@Override
		public void run() {
			System.out.println("DelayThread start!");
			while (isShow) {
				handler.sendEmptyMessage(0x00);
				try {
					System.out.println("DelayThread sleep 3s!");
					Thread.sleep(3 * 1000);
				} catch (InterruptedException e) {
					// Thread.currentThread().interrupt();
					e.printStackTrace();
				}
			}
			handler.sendEmptyMessage(0x01);
			System.out.println("DelayThread stop!");
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值