如何取消在android上以不同方法创建的Toast?
我有以下代码:
private Toast movieRecordToast;
private void displayNextMovie() {
if (movieRecordToast != null) movieRecordToast.cancel(); // cancel previous Toast (if user changes movies too often)
movieRecordToast = Toast.makeText(getApplicationContext(), "Next", Toast.LENGTH_SHORT);
movieRecordToast.show();
private void displayPrevMovie() {
if (movieRecordToast != null) movieRecordToast.cancel();
movieRecordToast = Toast.makeText(getApplicationContext(), "Prev", Toast.LENGTH_SHORT);
movieRecordToast.show();
但是,如果 displayNextMovie
被快速调用几次,然后 displayPrevMovie
被调用,“Next”Toast 仍然显示,并且只有在“Prev”显示之后。 看来取消功能不能正常工作。
I have the following code:
private Toast movieRecordToast;
private void displayNextMovie() {
if (movieRecordToast != null) movieRecordToast.cancel(); // cancel previous Toast (if user changes movies too often)
movieRecordToast = Toast.makeText(getApplicationContext(), "Next", Toast.LENGTH_SHORT);
movieRecordToast.show();
private void displayPrevMovie() {
if (movieRecordToast != null) movieRecordToast.cancel();
movieRecordToast = Toast.makeText(getApplicationContext(), "Prev", Toast.LENGTH_SHORT);
movieRecordToast.show();
But if displayNextMovie
is called quickly several times and then displayPrevMovie
is called, "Next" Toast is still shown and only after that "Prev" is displayed.
Looks like cancellation doesn't work properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以轻松地只保留一个
Toast
对象并取消当前的ToastToast
对象> 只要你愿意。在显示下一个Toast
之前,您可以使用Toast.setText()
函数更改文本。示例代码:
Instead of creating a new
Toast
object each time you want a new text displayed you can easily hold on to only oneToast
object and cancel the currentToast
whenever you want. Before the nextToast
is being displayed you can change text withToast.setText()
function.Sample code:
我认为有很多方法可以实现向用户显示下一个/上一个信息。我会完全放弃吐司,并使用下一个/上一个电影的名称来更新 TextView 的文本。这将消除你的问题,而且恕我直言,还可以带来更好的用户界面。
但是,如果您的设计要求确实要求 Toast 通知,请尝试:
I think there are many ways you can achieve displaying the next/prev info to the user. I would ditch the toasts altogether and update the text of a TextView with the name of next/prev movie. That would eliminate your problem and also IMHO makes for better UI.
However, if your design requirements do ask for toast notifications, try:
wroclai的解决方案非常棒!然而,当从长消息 Toast 变为短消息 Toast 时,它会搞砸 Toast,反之亦然。
要修复此问题而不是使用以前的对象重新创建它。所以代替这一行:
mToastText.setText(消息);
写这个:
myToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
动画看起来也更好:)
The wroclai's solution is excellent! However it screws the Toast when going form long message toast to short one and vice versa.
To fix this instead of using previous object recreate it. So instead of this line:
mToastText.setText(message);
write this one:
myToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
The animations also looks better :)