Sunday, January 1, 2012

Count Down Timer

Android provide a android.os.CountDownTimer. By new a CountDownTimer object, and overriding the call-back function onTick() and onFinish(), you can implement a count down timer easily.

Count Down Timer

package com.exercise.CountDownTimer;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;

public class AndroidCountDownTimerActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final TextView myCounter = (TextView)findViewById(R.id.mycounter);
        new CountDownTimer(30000, 1000) {

   @Override
   public void onFinish() {
    // TODO Auto-generated method stub
    myCounter.setText("Finished!");
   }

   @Override
   public void onTick(long millisUntilFinished) {
    // TODO Auto-generated method stub
    myCounter.setText("Millisecond Until Finished: " + String.valueOf(millisUntilFinished));
   }
         
        }.start();
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <TextView
        android:id="@+id/mycounter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


more:
Restart CountDownTimer


No comments: