您的位置:首页 > 移动开发 > Android开发

自己用来显示Toast的

2014-09-16 14:42 369 查看
<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!");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android Toast