gpt4 book ai didi

android - 删除线程 Toast 消息

转载 作者:行者123 更新时间:2023-11-30 04:01:19 25 4
gpt4 key购买 nike

从一个选项卡切换到另一个选项卡时,我试图“删除”Toast,因此假设暂停了聚焦的选项卡 Activity 。基本上我可以将取消方法应用于单个 Toast 对象,或将其分配给 null。这行得通。

重点是当我使用 TextView 并为 Toast 线程时,即使我停止线程,Toast 仍然可见。我从this point开始根据 this one 线程化 Toast 并尝试停止它.

如何停止线程并将 toast 从系统队列中移除,或者是否有更好的解决方案来实现该目标(例如,在单个 Activity 中使用多个 toast,在从一个 Activity 切换到另一个 Activity 时停止显示 toast)?


调用 Toast(这没问题):

private void showSingleToast(String toastText, int color, long duration_ms) {


if (mySingleToast instanceof Toast) {
mySingleToast.setText(toastText);

if (null != toastView)
if (toastView instanceof TextView)
toastView.setTextColor(color);

ToastExpander.showFor(mySingleToast, duration_ms);
}
}

线程化 Toast.show()

public class ToastExpander extends Thread {

public static final String TAG = "ToastExpander";

static Thread t;// = null;

// Must be volatile:
static volatile boolean stopFlag = false;
static long scan_freq = 300;

public static void showFor(final Toast aToast, final long durationInMilliseconds) {

aToast.setDuration(Toast.LENGTH_SHORT);

t = new Thread() {
long timeElapsed = 0l;

public void run() {
try {
while (timeElapsed <= durationInMilliseconds || !stopFlag) {
long start = System.currentTimeMillis();
aToast.show();
sleep(scan_freq);
timeElapsed += System.currentTimeMillis() - start;
}

// doesn't work: aToast.cancel();

} catch (InterruptedException e) {
Log.e(TAG, e.toString());
}
} /* end of "run" */

}; /* end of Thread */

t.start();



} /* end showFor */

public static void cancel() {
stopFlag = true;
}
}

尝试“删除”Toast(不起作用)

private void hideSingleToast() {
//hideTextView(toastView);
toastView = null;
ToastExpander.cancel();
mySingleToast.cancel();
//mySingleToast= null;


}

最佳答案

Toast 显示和取消是使用 handler 完成的。所以创建 toast 的线程应该一直运行到 toast 被取消,这样处理程序才能处理取消消息。因此,在 UI 线程中创建 Toast。

确保 mySingleToast 是在 Ui 线程中创建的

编辑:由于您是在 Ui 线程中创建 toast ,因此在您的情况下,看起来有太多 atoast.show() 排队。 LENGTH_SHORT 通常显示 2 秒。在那段时间里,你增加了近 6-7 场演出。这就是它继续显示的原因。

你可以做的是在 aToast.show 之前添加 aToast.cancel()

关于android - 删除线程 Toast 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12463712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com