首页 > 解决方案 > 更改片段后如何取消显示堆叠的吐司?

问题描述

我想在用户转到另一个片段后删除堆叠的 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;
}

标签: javaandroidtoast

解决方案


不要使用全局Toast对象,而是应该使用Toast. 所以,你可以一一取消。

toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast).show();
showSecondToast(toast).show();

toast1.cancel()


推荐阅读