CountDownTimer đếm ngược trong Android

COUNTDOWNTIMER TRONG ANDROID

CountDownTimer là class cung cấp chức năng giúp người lập trình tạo bộ đếm ngược trong Android. Để tạo một bộ đếm ngược đơn giản, chúng tôi sẽ giới thiệu với các bạn cách sử dụng CountDownTimer ngay sau đây.

may-tinh-android-0

 

Mục lục bài viết:

1. Khởi tạo một CountDownTimer

2. Các phương thức phổ biến trong CountDownTimer

3. Ví dụ tạo một bộ đếm ngược đơn giản

countdowntimer-trong-android-0

Dùng CountDownTimer tạo bộ đếm ngược

1. Khởi tạo một CountDownTimer

Đầu tiên, để tạo một bộ đếm ngược trên Android, ta cần phải khởi tạo bộ đếm CountDown:

CountDownTimer Timer = new CountDownTimer(30000, 1000) {
     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

Đoạn code trên ta hiểu rằng, một đối tượng CountDownTimer có là tên Timer được tạo ra kèm theo hai đối số 30000 và 1000. 30000 và 1000 có nghĩa là cứ 1000 mi-li giây thì phương thức onTick(long millisUntilFinished) sẽ được chạy một lần, cứ chạy như thế trong suốt 30000 mi-li giây. 30000 mili giây trôi qua, thì phương thức onFinish() sẽ chạy.

Phương thức onTick, kèm theo một đối số millisUntilFinished, đây là đối số cho ta biết số milli còn lại của bộ đếm (Ví dụ, bộ đếm trôi qua 2000 mi-li giây thì giá trị của millisUntilFinished còn 28000).

Phương thức onFinish, phương thức này được tự động gọi khi 30000 mi-li giây của bộ đếm trôi qua, đồng nghĩa với “Hết giờ”.

Tóm lại, đoạn code trên ta có thể hiểu nôm na: Một bộ đếm ngược 30 giây được tạo ra.

2. Các phương thức phổ biến trong CountDownTimer

Sau khi khởi tạo, chúng ta cần tìm hiểu một số phương thức được hỗ trợ trong class để dễ dàng làm việc với đối tượng này:

cancel()
//Huỷ bộ đếm

onFinish()
//Phương thức được gọi khi bộ đếm kết thúc

onTick(long millisUntilFinished)
//Phương thức được gọi khi bộ đếm chưa kết thúc

start()
//Bắt đầu bộ đếm

3. Ví dụ một tạo một bộ đếm ngược

Bài viết này, chúng tôi sẽ giới thiệu các bác cách tạo bộ đếm ngược đơn giản trên Android Studio. Đầu tiên, ta cần thiết kế giao diện trên activity_mail.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.baobao.demotimer.MainActivity">

    <Button
        android:text="START"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnStart"
        android:layout_marginLeft="60dp"
        android:layout_marginStart="60dp"
        android:layout_marginBottom="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="STOP"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnStop"
        android:layout_marginRight="60dp"
        android:layout_marginEnd="60dp"
        android:layout_marginBottom="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:inputType="number"
        android:text="0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textSize="80dp"
        android:id="@+id/edtTime"
        android:layout_marginTop="100dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

Cuối cùng là tiến hành code trên MainActivity.java. Sau đây là code mẫu:

package com.example.baobao.demotimer;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView edtTime;
    Button btnStart,btnStop;
    CountDownTimer Timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        edtTime =(EditText) findViewById(R.id.edtTime);
        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Timer = new CountDownTimer(Integer.parseInt(edtTime.getText().toString())*1000,1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        edtTime.setText(String.valueOf(millisUntilFinished/1000));
                    }

                    @Override
                    public void onFinish() {
                        edtTime.setText("Hết giờ");
                    }
                }.start();
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Timer.cancel();
            }
        });
    }
}
Cảm ơn các bạn đã theo dõi bài viết !