How can I show a toast for a specific duration?

MuraliGanesan picture MuraliGanesan · Jan 24, 2013 · Viewed 49.2k times · Source

This is the way I have to show the Toast for 500 milliseconds. Though, it's showing more than a second.

Toast.makeText(LiveChat.this, "Typing", 500).show(); 

How can I show Toast only for 500 milliseconds?

Answer

Raghav Sood picture Raghav Sood · Jan 24, 2013

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

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

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               toast.cancel(); 
           }
    }, 500);