Tuesday, January 20, 2015

Android CountDownTimer example

CountDown Timer
activity_main.xml code snippet

<TextView
 android:id="@+id/text_view"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Counter"
 android:textSize="75sp"
 android:textColor="#ff0000"
 >
</TextView>
<Button
 android:id="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Start Count Down"
 android:onClick="perform_action"
 android:textSize="35sp"
 >
</Button>
MainActivity.java code snippet

public void perform_action(View v)
{
 //call the custom function to start a new count down time
 // start time in milliseconds to count down
 long totalMilliseconds = 20000;
 //count down interval in milliseconds
 long interval = 1000;
 //1000 milliseconds = 1 second
 StartCountDownTimer(totalMilliseconds, interval);
}

public void StartCountDownTimer(long totalMilliseconds, long interval)
{
 //CountDownTimer(long millisInFuture, long countDownInterval)
 new CountDownTimer(totalMilliseconds, interval)
 {
  //textview widget to display count down
  TextView tv = (TextView) findViewById(R.id.text_view);
  public void onTick(long millisUntilFinished) {
   tv.setText(""+ millisUntilFinished / 1000);
  }
  public void onFinish()
  {
   //message to display when count down finished
   tv.setText("done!");
  }
 }.start();
}
Imported Class

import android.view.View;
import android.widget.TextView;
import android.os.CountDownTimer;
More android examples