Wednesday, 30 June 2010

Chronometer.OnChronometerTickListener()

Modify from the previous exercise "Android Chronometer", Chronometer.OnChronometerTickListener() is implemented. Chronometer.OnChronometerTickListener() is a callback that notifies when the chronometer has incremented on its own.

Chronometer.OnChronometerTickListener()

Inside Chronometer.OnChronometerTickListener(), the elapsed time in millisecons can be get from: SystemClock.elapsedRealtime() - myChronometer.getBase().

AndroidChronometer.java
package com.exercise.AndroidChronometer;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Toast;

public class AndroidChronometer extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
Button buttonStart = (Button)findViewById(R.id.buttonstart);
Button buttonStop = (Button)findViewById(R.id.buttonstop);
Button buttonReset = (Button)findViewById(R.id.buttonreset);

buttonStart.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myChronometer.start();
}});

buttonStop.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myChronometer.stop();

}});

buttonReset.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myChronometer.setBase(SystemClock.elapsedRealtime());

}});

myChronometer.setOnChronometerTickListener(
new Chronometer.OnChronometerTickListener(){

@Override
public void onChronometerTick(Chronometer chronometer) {
// TODO Auto-generated method stub
long myElapsedMillis = SystemClock.elapsedRealtime() - myChronometer.getBase();
String strElapsedMillis = "Elapsed milliseconds: " + myElapsedMillis;
Toast.makeText(AndroidChronometer.this, strElapsedMillis, Toast.LENGTH_SHORT).show();
}}
);
}
}



Download the files.

No comments:

Post a Comment