Android Count Down Timer in ActionBar

by 3:04 PM 0 comments
I'll show you how you can create a countdown timer and add it to your ActionBar, its really simple.

So first open menu.xml which is in res/values/menu.xml and add this item to it:

<item
            android:id="@+id/counter"
          
  android:title=""
            android:showAsAction="always">
</item>

then in your Activity that you want to show the countdown timer, replace the code in "public boolean onCreateOptionsMenu(Menu menu)" with the code below: 


long timer 10000;
public
 Boolean onCreateOptionsMenu(Menu menu) 
{

        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu, menu);

       
final MenuItem  counter = menu.findItem(R.id.counter);
        new CountDownTimer(timer, 1000) {

          public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished; 
            String  hms =  (TimeUnit.MILLISECONDS.toHours(millis))+":"+                    (TimeUnit.MILLISECONDS.toMinutes(millis) -             TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)))+":"+ (TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); 

            counter.setTitle(hms);
            timer = millis;
           
            }

        public void onFinish() {
            counter.setTitle("done!");
            }
         }.start();

         return  true;

 }




If you want to set the countdown time to a different value, then just change the timer variable to a different value, the timer should be in milliseconds

1 second = 1000 milliseconds
1 minute = 
60000 milliseconds
1 hour    = 3600000 milliseconds

This is how it looks like :
 



Unknown

Android Developer at Appsix LLC

I love stickers and reading books. A cool website that I've found was commitstrip.com
Currently reading: The pragmatic programmer, and The C programming language.
Currently working: an android app, and on a web project with laravel.
Im a 9gag enthusiast.
I write code at work and at home for fun or out of pure boredom.
Programming Languages that I've worked with: Java PHP C# PLSQL JavaScript
Thanks for reading.



0 comments :

Post a Comment