Toast with specific duration

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();
        }}}}
    
asked by anonymous 31.05.2017 / 20:13

3 answers

2

This can not be done. To show for a time less 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);
    
31.05.2017 / 20:23
1

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

To meet what you need, we need to do something more in the Brazilian way. It would look 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 get a time counter x (10 seconds in the case), which will keep firing toast during that time. Once finished, it will cancel the toast and stop displaying it. It's a trick.

If you'd like to use a lib , which I use in my projects, which makes it easier, you can use this one that owns method

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

where 5 is the value in seconds for the display time.

    
31.05.2017 / 20:24
0

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

    
31.05.2017 / 20:21