Toast with specific duration

Asked

Viewed 746 times

0

How to put this Toast to last only a few seconds? For example, 10 seconds.

if (mEmail.equals(email) && mPassword.equals(password)) {


                    Intent intent = new Intent(LoginActivity.this, MainActivity2.class);
                    intent.putExtra("result", result);
                    startActivity(intent);

                }

                else {


                    Toast.makeText(LoginActivity.this,"Email ou senha inválido(s)",Toast.LENGTH_SHORT).show();


                }
            }



        } catch (JSONException e) {
            e.printStackTrace();
        }}}}
  • please mark the correct answer if I have helped you.

3 answers

2

This cannot be done. To show for a shorter time than Toast.LENGTH_SHORT, you must cancel it after the desired time. Something like:

   final Toast toast = Toast.makeText(getApplicationContext(), "This message will disappear     in half second", Toast.LENGTH_SHORT);
        toast.show();

        Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
               @Override
               public void run() {
                   toast.cancel(); 
               }
        }, 500);
  • Thank you, it worked properly !

  • Very good! Please mark as the correct answer if I have helped you.

1

For Toast there are only 2 flags: LENGTH_SHORT and LENGTH_LONG. That is, are values already defined.

To meet what Oce needs, we need to do something more the Brazilian way. It would be something like this:

private Toast mToastToShow;
public void showToast(View view) {

int toastDurationInMilliSeconds = 10000;
mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", 
Toast.LENGTH_LONG);

CountDownTimer toastCountDown;
 toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000) 
 {
  public void onTick(long millisUntilFinished) {
     mToastToShow.show();
  }
  public void onFinish() {
     mToastToShow.cancel();
     }
 };

mToastToShow.show();
toastCountDown.start();
}

That is, you will have an x time counter (10 seconds in the case), which will be firing Oast during that time. Once finished, it will cancel Toast and stop displaying it. It’s a trick.

If you want to use a lib, that I use in my projects, which facilitates this can use this one that has the method

UtilsPlus.getInstance().toast("Hello World!", 5);

where 5 is the value in seconds for display time.

0

Toasts have only two possible durations: Toast.LENGTH_SHORT and Toast.LENGTH_LONG. These values are treated as flags and not as durations. It is not possible to manually choose an exact duration time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.