Search code examples
androidtoast

Android : How to repeat a Toast every second


I am using a toast for Count Down Timer, so the toast should change it's text in every second. I use this to display the toast for exactly 1 second but i want the toast to repeat itself. Hope i make you understand.

 toast =    Toast.makeText(getApplicationContext(), text.getText().toString(), Toast.LENGTH_SHORT);             toast.show();
Handler handler = new Handler();
    handler.postDelayed 
               (new Runnable() {

              @Override
                 public void run() {
                            toast.cancel();
            }
        }, 1000);

Solution

  • This will show a new toast every second for exactly one second.

        int count = 100; //Declare as inatance variable
    
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
    
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
    
                    @Override
                    public void run() {
                        final Toast toast = Toast.makeText(
                                getApplicationContext(), --count + "",
                                Toast.LENGTH_SHORT);
                        toast.show();
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
    
                            @Override
                            public void run() {
                                toast.cancel();
                            }
                        }, 1000);
    
                    }
                });
            }
        }, 0, 1000);