使 android toast 不可取消

Make android toast not cancellable

我正在我的应用程序中展示祝酒辞。问题是在某些设备(Samsung galaxy s6)中,toast 在触摸屏幕时被取消。此问题不会发生在其他设备 (Nexus 5)

这是我的代码

LayoutInflater li = getLayoutInflater();
View layout = li.inflate(R.layout.popup_tutorial_privado, (ViewGroup)findViewById(R.id.popup));
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

toast 在小弹出窗口中提供有关操作的简单反馈。它仅填充消息所需的 space 数量,并且当前 activity 保持可见和交互。 toast 不与用户交互,就像 "comes and go" 你不能将它设置为可取消的 true 或 false。 你应该使用 Dialogs 来实现你想要的。

退一步

如果您需要更多控制权,请完全避免使用 Toast,并使用会在 n 时间后自动消失的 Dialog。你可以写一个像这个一样简单的方法,它会产生一些功能上等同于 Toast 的东西,但可以更自由地控制它何时以及如何被取消。

public void customToast(String message, int duration){
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.custom_toast);
    dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    dialog.setCancelable(false);

    //Customize the views, add actions, whatever
    ((TextView)dialog.findViewById(R.id.message)).setText(message);
    dialog.show();
    //Auto cancel the dialog after `duration`
    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            dialog.cancel();
        }
    },duration);
}

演示

备注

如果您希望对话框显示的时间与长吐司持续的确切时间相同,请使用 3500,因为 private static final int LONG_DELAY = 3500;

但是等等!对话框获得焦点,我需要保留它!

好吧,好吧,你可能在 EditText 里面写字,而 Dialog 就像 Toast 一样控制你的焦点,你的键盘隐藏起来,一切都丢失了。为防止这种情况,只需设置一个额外的标志,告诉 Dialog 它不可聚焦,并且不应尝试请求它。

dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

请记住,如果您通过观察 EditText 中的文本变化来显示 Toast,您应该保留某种标志,以了解它是否正在显示或已经显示显示或其他任何内容,否则您将得到多个对话框。

根据文档的建议:

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout.

对于您解释的行为,您确实使用了无限时间的小吃店 Snackbar documentation