[英]Show toast only if it's different from the existing toast
因此,我的目标是仅在没有显示Toast消息或显示的消息与我要发送的消息不同的情况下,向用户显示Toast消息。 如果该消息与向用户显示的消息相同,则我不希望该消息通过(因为这毫无意义)。
为了实现这个目标,我找到了这篇文章,内容关于如何仅在未显示吐司的情况下显示吐司。
我已修改代码以同时满足这两个要求。
private Toast toast;
public void showAToast (String st, boolean isLong){
try{
toast.getView().isShown();
String text = ((TextView)((LinearLayout)toast.getView()).getChildAt(0)).getText().toString();
if(!text.equalsIgnoreCase(st)){
//New message, show it after
if(isLong){
toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_LONG);
} else {
toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_SHORT);
}
toast.show();
}
} catch (Exception e) {
//New message
if(isLong){
toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_LONG);
} else {
toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_SHORT);
}
toast.show();
}
}
我的问题是,如果最后一个吐司消息与想要通过的消息相同,则任何消息都不会通过。
不知道为什么会这样,但是我在方法中放入了一些调试消息以找出问题所在。
消息说,如果在应用程序的生存期内发送了任何Toast消息,则toast.getView()。isShown()不会引发异常(假定表示未显示Toast)。
所以我的问题是,我该如何解决? 当然,必须有一种方法来实现此所需功能。
我之前在stackoverflow中看到过这一点,但是它并不像我想要的那么干净。 我们实施了双重吐司方法,在两种吐司之间交替进行。 首先,我们在OnCreate之前为活动定义敬酒:
Toast toast0;
Toast toast1;
private static boolean lastToast0 = true;
In the OnCreate:
toast0 = new Toast(getApplicationContext());
toast0.cancel();
toast1 = new Toast(getApplicationContext());
toast1.cancel();
//And finally, when I need to display the toast and cancel the prior toast at the same time I use something similar to:
if (lastToast0) {
toast0.cancel();
toast1.setDuration(Toast.LENGTH_LONG);
toast1.setText("new message");
toast1.show();
lastToast0 = false;
} else {
toast1.cancel();
toast0.setDuration(Toast.LENGTH_LONG);
toast0.setText("new message");
toast0.show();
lastToast0 = true;
}
// If you need to just cancel an existing toast (before it times out) use:
toast0.cancel();
toast1.cancel();
报价单
您可以使用相同的Toast
实例显示消息。 如果消息相同,则吐司将不会显示两次,否则,文本将简单地更改为最新的消息。
Toast mToast;
public void showToast(CharSequence message, int during){
if (mToast == null) {
mToast = Toast.makeText(getApplicationContext(), message, during);
} else {
mToast.setText(message);
}
mToast.show();
}
-↓---↓----↓---更新-↓----↓---↓-↓
对不起,我想念你的意思。
我阅读了Toast的源代码,因为该视图已添加到WindownManager中,所以我们无法获得视图状态。到目前为止,我还找不到一种方法来指出是否显示了Toast。
但是您可以实现自己的Toast使用服务,它类似于应用程序上方显示的Toast。 可能会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.