英文:
How to cancel stacked toast from showing after changing fragment?
问题
我想在用户切换到另一个片段后移除堆叠的Android Toast。我有一些被堆叠的片段,每个片段中都有两个按钮,触发不同的Toast消息。当片段的操作完成并且用户导航到另一个片段或按下返回按钮时,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;
}
英文:
I want to remove stacked Android Toasts after the user goes to another Fragment. I have Fragments that are stacked and in every Fragment, I have two buttons which triggers different Toast message. When operations of a Fragment is done and the user navigates to another Fragment or press back button Toasts are kept showing. This mainly happens when the user clicks buttons too fast and force Toasts to stack.
Or when I instantiate global Toast objects and call cancel() than both of toasts stop from showing in that lifecycle of a fragment no matter how many times the user tap button.
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;
}
答案1
得分: 1
不要使用全局的 Toast
对象,而是应该使用多个 Toast
实例。这样,你可以逐个取消它们。
toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast1).show();
showSecondToast(toast2).show();
toast1.cancel();
英文:
Do not use global Toast
object instead you should use multiple instances of Toast
. So, you can cancel it one by one.
toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast).show();
showSecondToast(toast).show();
toast1.cancel()
答案2
得分: 1
为了避免叠加的弹出消息,我重用了一个单一的消息提示框:
Toast toast;
protected void showToast(final String text) {
if (toast == null)
toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
else
toast.setText(text); // 比取消后创建新消息提示框更流畅的过渡效果
toast.show();
}
@Override
public void onPause() {
if(toast != null)
toast.cancel();
super.onPause();
}
英文:
to avoid stacked toasts I reuse a single toast
Toast toast;
protected void showToast(final String text) {
if (toast == null)
toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
else
toast.setText(text); // smoother transition than cancel + new toast
toast.show();
}
@Override
public void onPause() {
if(toast != null)
toast.cancel();
super.onPause();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论