我有几个 SeekBar
和 onSeekBarProgressStop()
,我想显示一个 Toast
消息。
但是,如果在 SeekBar
上我快速执行操作,那么 UI 线程会以某种方式阻塞并且 Toast
消息会等待直到 UI 线程空闲。
现在我担心的是,如果 Toast
消息已经显示,则要避免新的 Toast
消息。或者他们是我们检查 UI 线程当前空闲的任何条件,然后我将显示 Toast
消息。
我尝试了两种方式,使用 runOnUIThread()
并创建新的 Handler
。
最佳答案
我已经尝试了很多方法来做到这一点。起初我尝试使用 cancel()
,但对我没有任何效果(另见 this answer)。
使用 setDuration(n)
我也不会去任何地方。通过记录 getDuration()
发现它的值为 0(如果 makeText()
的参数是 Toast.LENGTH_SHORT
)或1(如果 makeText()
的参数是 Toast.LENGTH_LONG
)。
最后我尝试检查 toast 的 View 是否 isShown()
。当然,如果没有显示 toast 则不是,但更重要的是,在这种情况下,它会返回一个 fatal error 。所以我需要尝试捕捉错误。
现在,如果显示 toast,isShown()
返回 true。
利用 isShown()
我想出了方法:
/**
* <strong>public void showAToast (String st)</strong></br>
* this little method displays a toast on the screen.</br>
* it checks if a toast is currently visible</br>
* if so </br>
* ... it "sets" the new text</br>
* else</br>
* ... it "makes" the new text</br>
* and "shows" either or
* @param st the string to be toasted
*/
public void showAToast (String st){ //"Toast toast" is declared in the class
try{ toast.getView().isShown(); // true if visible
toast.setText(st);
} catch (Exception e) { // invisible if exception
toast = Toast.makeText(theContext, st, toastDuration);
}
toast.show(); //finally display it
}
关于android - 如果已经显示了一个 Toast,如何避免 Toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6925156/