4

当我的提交按钮被点击时,它会调用一个方法来检查某个 EditText 是否为空,并相应地显示一条 toast 消息作为错误消息。但是,如果我快速点击提交,它会“排队”很多 toast 消息。我怎样才能防止这种情况?

这是我的方法:

private void checkName() {
    if (etName.getText().toString().isEmpty()) {
        Toast toast = Toast.makeText(this, "Please enter your name", Toast.LENGTH_LONG);
        toast.show();
    } else {
        submit();
    }
}
4

1 回答 1

6

What happens is you are creating new toasts each time checkName() is called, hence they are "queued" by the system and shown one after another. You can try the following to ensure you are just making one toast and simply show it when needed:

Toast mToast;

private void checkName() {
    if (etName.getText().toString().isEmpty()) {
        if (mToast == null) { // Initialize toast if needed
                mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
        }
        mToast.setText("Please enter your name"); // Simply set the text of the toast
        mToast.show(); // Show it, or just refresh the duration if it's already shown
    } else {
        submit();
    }
}
于 2013-05-18T07:20:52.003 回答