toast.cancel()似乎不起作用

时间:2017-05-10 15:25:40

标签: android toast

我正试图在屏幕上仍然显示实例时阻止显示/堆叠的Toast消息。我按下“减量按钮”,它将数量减少1,但如果数量等于1,则会显示一个吐司信息。现在的问题是,每次按下“减量按钮”时,吐司信息都会堆叠起来。这是我尝试过的,我不确定如何防止堆积问题:

Toast toastMessage;    

...

public void decrementQty(View view) {
        if (quantity == 1) {
            if (toastMessage != null) {
                toastMessage.cancel();
            }
            toastMessage.makeText(this, "You must order at least 1", Toast.LENGTH_SHORT).show();
            return;
        }
        quantity -= 1;
        displayQuantity(quantity);
    }

1 个答案:

答案 0 :(得分:1)

尝试添加else分支

public void decrementQty(View view) {
        if (quantity == 1) {
            if (toastMessage != null) {
                toastMessage.cancel();
                toastMessage = null;
            } else {
               toastMessage = Toast.makeText(this, "You must order at least 1", Toast.LENGTH_SHORT)
               toastMessage.show();
            }
            return;
        }
        quantity -= 1;
        displayQuantity(quantity);
    }