java - 更改片段后如何取消显示堆叠的吐司?
问题描述
我想在用户转到另一个片段后删除堆叠的 Android Toast。我有堆叠的片段,在每个片段中,我有两个按钮触发不同的 Toast 消息。当一个 Fragment 的操作完成并且用户导航到另一个 Fragment 或按下返回按钮时,Toast 会一直显示。这主要发生在用户点击按钮太快并强制 Toast 堆叠时。
或者当我实例化全局 Toast 对象并调用 cancel() 时,无论用户点击按钮多少次,两个 toast 都不会在片段的生命周期中显示。
toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast1).show();
showSecondToast(toast2).show();
private Toast showFirstToast(Toast toast){
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout_correct, (ViewGroup)
getActivity().findViewById(R.id.toast_layout));
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
return toast;
}
解决方案
不要使用全局Toast
对象,而是应该使用Toast
. 所以,你可以一一取消。
toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast).show();
showSecondToast(toast).show();
toast1.cancel()
推荐阅读
- token - Monaco Editor 中 registerDocumentSemanticTokensProvider 和 setMonarchTokensProvider 的区别?
- shell - 直接从 Git Repo 获取 Json 的所有键作为列表
- javascript - 如何以与现有元素相同的顺序推送数组元素
- html - 下拉菜单不对齐(纯 CSS)
- sql - EF CORE 代码第一主键组合键主键
- html - 如何使用 CSS 修复顶部的表头?
- c# - 如何使用 ServiceStack.Text 加载从包含实体的字典创建的 CSV 文件
- python - 24/7 Python selenium "while true:" 脚本无法执行 driver.get("URL")
- javascript - 如何比较两个数组并添加新的属性和值
- linux - linux上的WCF WsHttpBinding