Hướng dẫn và ví dụ Android Chronometer
Xem thêm các chuyên mục:

Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.


Trong Android, Chronometer (Đồng hồ bấm giờ) là một thành phần giao diện mô phỏng một thiết bị đo thời gian (timer) đơn giản.

Chú ý: Thành phần Chronometer không sẵn có trên Palette của cửa sổ thiết kế, vì vậy bạn cần sử dụng đoạn XML dưới đây để thêm nó vào trong giao diện.
<Chronometer
android:id="@+id/simpleChronometer"
android:countDown="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Chronometer
android:id="@+id/simpleChronometer"
android:countDown="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
android:countDown
Thuộc tính này chỉ định rằng Chronometer này là đếm lùi (counts down) hay đếm xuôi (counts up), giá trị của nó là true/false.
<!-- Counts Up -->
<Chronometer
android:id="@+id/simpleChronometer"
android:countDown="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- Counts Down -->
<Chronometer
android:id="@+id/simpleChronometer"
android:countDown="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
android:format
Thuộc tính này chỉ định một chuỗi định dạng thời gian (time format string) cho Chronometer.
Theo mặc định, Chronometer sẽ hiển thị thời gian theo định dạng "MM:SS" khi thời gian nhỏ hơn 1 giờ, hoặc "H:MM:SS" nếu thời gian lớn hơn 1 giờ. Giá trị của thuộc tính android:format phải có dạng "Text1 %s Text2", và khi Chronometer hiển thị thời gian bạn sẽ nhận được chuỗi có định dạng "Text1 MM:SS Text2" hoặc "Text1 H:MM:SS Text2".

Chronometer Methods
long getBase()
void setBase(long base)
String getFormat()
void setFormat(String format)
boolean isCountDown()
void setCountDown(boolean countDown)
boolean isTheFinalCountDown()
void start()
void stop()
setBase(long base)

Phương thức này chỉ có ích đối với các Chronometer đếm xuôi (count up), được sử dụng để sét đặt thời điểm mà Chronometer tham chiếu đến (Tương ứng với giá trị 00:00).
Tham số base là số mili giây kể từ khi hệ thống được khởi động, bao gồm cả thời gian ngủ của thiết bị. Nếu bạn sử dụng Android Emulator (Trình giả lập của Android) thời điểm máy tính khởi động sẽ được coi là gốc của tọa độ.
// Returns milliseconds since system boot, including time spent in sleep.
long elapsedRealtime = SystemClock.elapsedRealtime();
// Set the time that the count-up timer is in reference to.
this.chronometer.setBase(elapsedRealtime);
this.chronometer.start();
setFormat(String format)
Theo mặc định, Chronometer sẽ hiển thị thời gian theo định dạng "MM:SS" khi thời gian nhỏ hơn 1 giờ, hoặc "H:MM:SS" nếu thời gian lớn hơn 1 giờ. Giá trị của tham số format phải có dạng "Text1 %s Text2", và khi Chronometer hiển thị thời gian bạn sẽ nhận được chuỗi có định dạng "Text1 MM:SS Text2" hoặc "Text1 H:MM:SS Text2".

Nếu bạn muốn có một tùy biến sâu hơn về định dạng hiển thị thời gian của Chronometer bạn có thể xem một ví dụ ở phía cuối bài viết này.
-
TODO
Chúng ta bắt đầu với một với một Chronometer đếm xuôi (count up) đơn giản, ứng dụng này có thể sử dụng để đo thời gian chạy của một vận động viên.

OK, Trên Android Studio tạo mới project:
- File > New > New Project > Empty Activity
- Name: ChronometerExample
- Package name: org.o7planning.chronometerexample
- Language: Java
Giao diện của ví dụ:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView_info"
android:layout_width="378dp"
android:layout_height="24dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:gravity="center_horizontal"
android:text="(Info)"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Chronometer
android:id="@+id/chronometerExample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:textSize="60sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView_info" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/chronometerExample">
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:layout_weight="1"
android:text="Start"
android:textAllCaps="false" />
<Button
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:layout_weight="1"
android:text="Stop"
android:textAllCaps="false" />
<Button
android:id="@+id/button_resetBaseTime"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:layout_weight="1"
android:text="Reset"
android:textAllCaps="false" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.chronometerexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private TextView textViewInfo;
private Chronometer chronometer;
private Button buttonStart;
private Button buttonStop;
private Button buttonResetBaseTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textViewInfo = (TextView) findViewById(R.id.textView_info);
this.chronometer = (Chronometer)findViewById(R.id.chronometerExample);
this.buttonStart = (Button)findViewById(R.id.button_start);
this.buttonStop = (Button)findViewById(R.id.button_stop);
this.buttonResetBaseTime = (Button)findViewById(R.id.button_resetBaseTime);
this.buttonStop.setEnabled(false);
this.buttonResetBaseTime.setEnabled(false);
this.buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doStart();
}
});
this.buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doStop();
}
});
this.buttonResetBaseTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doResetBaseTime();
}
});
}
// @totalMilliseconds: milliseconds since system boot, including time spent in sleep.
private void showInfo(long totalMilliseconds) {
// Seconds
long totalSecs = totalMilliseconds / 1000;
// Show Info
long hours = totalSecs / 3600;
long minutes = (totalSecs % 3600) / 60;
long seconds = totalSecs % 60;
this.textViewInfo.setText("Base Time: " + totalSecs +" ~ " + hours + " hours " + minutes+" minutes " + seconds + " seconds");
}
private void doStart() {
// Returns milliseconds since system boot, including time spent in sleep.
long elapsedRealtime = SystemClock.elapsedRealtime();
// Set the time that the count-up timer is in reference to.
this.chronometer.setBase(elapsedRealtime);
this.chronometer.start();
this.showInfo(elapsedRealtime);
//
this.buttonStart.setEnabled(false);
this.buttonStop.setEnabled(true);
this.buttonResetBaseTime.setEnabled(true);
}
private void doStop() {
this.chronometer.stop();
//
this.buttonStart.setEnabled(true);
this.buttonStop.setEnabled(false);
this.buttonResetBaseTime.setEnabled(false);
}
private void doResetBaseTime() {
// Returns milliseconds since system boot, including time spent in sleep.
long elapsedRealtime = SystemClock.elapsedRealtime();
// Set the time that the count-up timer is in reference to.
this.chronometer.setBase(elapsedRealtime);
this.showInfo(elapsedRealtime);
}
}
Ví dụ về một Chronometer đếm ngược (Count down).


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:background="#D7F3C9"
android:gravity="center_horizontal"
android:text="Count Down Chronometer"
app:layout_constraintHorizontal_bias="0.047"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Chronometer
android:id="@+id/chronometerCountDown"
android:countDown="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:textSize="60sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView_1" />
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/chronometerCountDown" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.chronometerexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class MainActivity extends AppCompatActivity {
private Button buttonStart;
private Chronometer chronometerCountDown;
private int counter = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.chronometerCountDown = (Chronometer) findViewById(R.id.chronometerCountDown);
this.buttonStart = (Button) findViewById(R.id.button_start);
this.chronometerCountDown.setText(counter + "");
this.buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doStart();
}
});
// This listener will customize the chronometer text content.
// It will show number from 10 to 0 repeatedly.
this.chronometerCountDown.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
onChronometerTickHandler();
}
});
}
private void onChronometerTickHandler() {
if(this.counter < 0) {
this.counter = 10;
}
this.chronometerCountDown.setText(counter + "");
this.counter--;
}
private void doStart() {
this.chronometerCountDown.start();
}
}
Ví dụ dưới đây cho phép bạn tùy biến văn bản hiển thị trên Chronometer:


main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView_2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:background="#D7F3C9"
android:gravity="center_horizontal"
android:text="Custom Format"
app:layout_constraintHorizontal_bias="0.047"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Chronometer
android:id="@+id/chronometer_customFormat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView_2" />
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/chronometer_customFormat" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.chronometerexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class MainActivity extends AppCompatActivity {
private Button buttonStart;
private Chronometer chronometerCustomFormat;
private int counter = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.chronometerCustomFormat = (Chronometer) findViewById(R.id.chronometer_customFormat);
this.chronometerCustomFormat.setText("Please click start!");
this.buttonStart = (Button) findViewById(R.id.button_start);
this.buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doStart();
}
});
this.chronometerCustomFormat.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
onChronometerTickHandler();
}
});
}
private void onChronometerTickHandler() {
long delta = SystemClock.elapsedRealtime() - this.chronometerCustomFormat.getBase();
int h = (int) ((delta / 1000) / 3600);
int m = (int) (((delta / 1000) / 60) % 60);
int s = (int) ((delta / 1000) % 60);
String customText = h +" hours " + m +" minutes " + s +" seconds";
this.chronometerCustomFormat.setText(customText);
}
private void doStart() {
long base = SystemClock.elapsedRealtime();
this.chronometerCustomFormat.setBase(base);
this.chronometerCustomFormat.start();
}
}