Trước khi đi vào ví dụ, chúng ta nên biết DatePicker là gì và nó hoạt động như thế nào trong Android. DatePicker là subclass của FrameLayout và cho phép chọn ngày, tháng và năm.
Ví dụ này minh họa cách sử dụng Android Date Change Listener.
Bước 1
Tạo một dự án mới trong Android Studio, vào File → New Project và điền đầy đủ thông tin cần thiết để tạo dự án mới.
Bước 2
Thêm mã sau vào res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginBottom="36dp" /> </RelativeLayout>
Trong mã trên, chúng ta khai báo DatePicker để chọn ngày. Khi bạn chọn ngày, nó sẽ hiển thị ngày hiện tại trên Toast message.
Bước 3
Thêm mã sau vào src/MainActivity.java
package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.DatePicker; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DatePicker datePicker = findViewById(R.id.datePicker); datePicker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText(MainActivity.this," You are changed date is : "+dayOfMonth +" - "+monthOfYear+ " - "+year,Toast.LENGTH_LONG).show(); } }); } }Trong mã trên, khi bạn thay đổi ngày dùng DateChangedListener, nó sẽ hiển thị ngày, tháng, năm đã thay đổi trên Toast message.
Bước 4
Không cần thay đổi manifest.xml.
Hãy thử chạy ứng dụng. Giả sử bạn đã kết nối thiết bị Android thực tế với máy tính. Để chạy ứng dụng từ Android Studio, mở một file activity của dự án và nhấn biểu tượng Run
từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn và kiểm tra thiết bị sẽ hiển thị màn hình mặc định:


Trong ví dụ trên cho thấy, khi bạn thay đổi ngày nó sẽ hiển thị ngày đã thay đổi trong toast message.