sandalone
sandalone

Reputation: 41759

Show only one Toast in click event?

I want to notify a user that he has reached a minimum value. The value is set via the button click. If he continues to click on a button, when a minimum value has been reached, Toasts start appearing and queuing so it takes a long time for all to disappear.

btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
             if (value < MIN_VALUE) {
                    Toast.makeText(MyActivity.this, "You have reached the minimum value",
                            Toast.LENGTH_SHORT).show();
                }
        });

How can I make only 1st toast to appear on button click? This way if a user keeps clicking the button, no other toasts will appear.

Upvotes: 1

Views: 6154

Answers (3)

pvllnspk
pvllnspk

Reputation: 5767

public static void showToast(Context cont, String message) {
    if (mToast == null) {
        mToast = Toast.makeText(cont, message, Toast.LENGTH_SHORT);
    }
    if (!mToast.getView().isShown()) {
        mToast.setText(message);
        mToast.show();
    }
}

Upvotes: 5

Andro Selva
Andro Selva

Reputation: 54322

Once he reaches his limit, display the toast and disable the button's onClick by overridding button.setEnabled(false);

So, now the user won't be able to click the button more than once.

Upvotes: 3

MByD
MByD

Reputation: 137322

Add a flag that indicates whether the button was already pressed or not:

btn.setOnClickListener(new View.OnClickListener() {
        boolean pressed = false;
        public void onClick(View view) {
         if ((value < MIN_VALUE) && (!pressed)) {
                Toast.makeText(MyActivity.this, "You have reached the minimum value",
                        Toast.LENGTH_SHORT).show();
                pressed = true;
            }
    });

Upvotes: 6

Related Questions