Android: DatePicker trong Android


Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên

DatePicker trong Android cho phép bạn lựa chọn date bao gồm ngày, tháng, và năm trong Custom UI của bạn. Với tính năng này, Android cung cấp các thành phần DatePicker và DatePickerDialog.

Bài viết này sẽ minh họa cách sử dụng của DatePicker thông qua DatePickerDialog. DatePickerDialog là một hộp thoại đơn giản chứa DatePicker.

Để hiển thị DatePickerDialog, bạn phải truyền DatePickerDialog ID tới phương thức với cú pháp như sau:

showDialog(id_of_dialog)

Ví dụ:

showDialog(1);

Khi gọi phương thức showDialog này, một phương thức khác cũng tự động được gọi là onCreateDialog. Vì thế, chúng ta phải ghi đè cả phương thức đó. Cú pháp như sau:

@Override
protected Dialog onCreateDialog(int id) {
  if (id == 1) {
    return new DatePickerDialog(this, dateSetListener, year, month, day);
  }
  return null;
}

Trong bước cuối cùng, bạn phải đăng ký DatePickerDialog Listener và ghi đè phương thức onDateSet của nó. Phương thức onDateSet này chứa ngày, tháng, và năm đã được cập nhật. Cú pháp như sau:

DatePickerDialog.OnDateSetListener dateSetListener=new DatePickerDialog.OnDateSetListener() {
  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    showDate(year,month+1,dayOfMonth);
  }
};

Ngoài các thuộc tính date, đối tượng DatePicker cũng được truyền vào trong hàm này. Bạn có thể sử dụng các phương thức sau của DatePicker để thực hiện các hoạt động khác.

Stt Phương thức & Miêu tả
1 getDayOfMonth()

Phương thức này lấy ngày đã chọn của tháng

2 getMonth()

Phương thức này lấy tháng đã chọn

3 getYear()

Phương thức này lấy năm đã chọn

4 setMaxDate(long maxDate)

Phương thức này thiết lập date tối đa được hỗ trợ bởi DatePicker (giá trị mili giây) từ 1/1/1970 00:00:00 trong getDefault()

5 setMinDate(long minDate)

Phương thức này thiết lập date tối thiểu được hỗ trợ bởi DatePicker (giá trị mili giây) từ 1/1/1970 00:00:00 trong getDefault()

6 setSpinnersShown(boolean shown)

Phương thức này thiết lập xem có hay không spinner được hiển thị

7 updateDate(int year, int month, int dayOfMonth)

Phương thức này cập nhật date hiện tại

8 getCalendarView()

Phương thức này trả về calendar view

9 getFirstDayOfWeek()

 

Phương thức này trả về ngày đầu tiên của tuần

 

Ví dụ áp dụng

Sau đây là nội dung của file MainActivity.java:

package v1study.com.datepicker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
  Calendar calendar;
  TextView textViewResult, textViewLabelForResult;
  Button buttonSetDate;
  int year, month, day;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonSetDate = findViewById(R.id.buttonSetDate);
    textViewResult = findViewById(R.id.textViewResult);
    textViewLabelForResult=findViewById(R.id.textViewLalbelForResult);
    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);
    showDate(year, month + 1, day);

    buttonSetDate.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showDialog(1);
        Toast.makeText(getApplicationContext(), "Bn hãy chn 1 ngày!", 3000).show();
      }
    });
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    if (id == 1) {
      return new DatePickerDialog(this, dateSetListener, year, month, day);
    }
    return null;
  }

  DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
      textViewLabelForResult.setText("Bn đã chn ngày:");
      showDate(year, month + 1, dayOfMonth);
    }
  };

  private void showDate(int year, int month, int day) {
    textViewResult.setText(new StringBuilder().append(day > 9 ? day : "0" + day).append("/").append(month > 9 ? month : "0" + month).append("/").append(year));
  }
}

Sau đây là nội dung của file res/layout/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:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ngay_thang_nam_label"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:textSize="24sp"
    android:textStyle="bold"
    android:textColor="#8BC34A"
    app:layout_constraintVertical_bias="0.559"
    android:id="@+id/textViewLalbelForResult"/>

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/textViewResult"
    app:layout_constraintVertical_bias="0.65"
    android:textSize="30sp"
    android:textStyle="bold"
    android:textColor="#FF9800"/>

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/chon_ngay"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/buttonSetDate"
    app:layout_constraintVertical_bias="0.367"
    android:textSize="30sp"
    android:textStyle="bold"
    android:textColor="#009688"/>

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/nhan_nut_ben_duoi_de_chon_ngay"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/textViewLabel"
    app:layout_constraintVertical_bias="0.264"
    android:textSize="18sp"
    android:textStyle="bold"
    android:textColor="#00BCD4"/>

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/datepicker_demo"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/textViewTitle"
    app:layout_constraintVertical_bias="0.12"
    android:textSize="30sp"
    android:textStyle="bold"
    android:textColor="#4CAF50"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Và đây là nội dung của res/values/string.xml:

<resources>
  <string name="app_name">DatePickerV1Study</string>
  <string name="nhan_nut_ben_duoi_de_chon_ngay">Nhn nút bên dưới đchn ngày</string>
  <string name="datepicker_demo">DatePicker Demo</string>
  <string name="chon_ngay">Chn ngày</string>
  <string name="ngay_thang_nam_label">Hôm nay là ngày:</string>
</resources>

Chạy ứng dụng:

Date Picker trong Android

Bạn nhấn vào nút "CHỌN NGÀY" sẽ xuất hiện như sau:

Date Picker trong Android

Bạn chọn một ngày/tháng/năm rồi nhấn nút "OK" sẽ được kết quả dạng như sau:

Date Picker trong Android

» Tiếp: Alert Dialog trong Android
« Trước: TimePicker trong Android
Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên
Copied !!!