Lập trình Android - DatePicker

DatePicker trong Android

DatePicker là một ui widget thường được sử dụng chọn ngày. DatePicker cho phép chọn ngày, tháng và năm.Để hình dung Dialog này như thế nào thì các bạn có thể thấy hình dạng của DatePickerDialog dưới đây.

android.widget.DatePicker là lớp con của lớp FrameLayout.

DatePicker code trong XML:

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>

Các phương thức thường dùng của DatePicker

1. setSpinnersShown(boolean shown): Phương thức này thường sử dụng để hiện thi DatePicker ở dạng spinner hay không. Trong phương thức này chúng ta có thể thiết lập giá trị true hoặc false. Nếu giá trị là false thì spinner không hiển thị. Mặc định là true

Code sau cách sử dụng phương thức setSpinnersShow() false

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker

simpleDatePicker.setSpinnersShown(false); // set false value for the spinner shown function

2. getDayOfMonth(): Phương thức này được sử dụng để lấy ngày trong  tháng từ DatePicker. Phương thức này trả về một số nguyên.

Code sau lấy ngày trong tháng từ DatePicker

/*Add in Oncreate() funtion after setContentView()*/
DatePicker simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker); // initiate a date picker
int day = simpleDatePicker.getDayOfMonth(); // Lấy ngày trong tháng

3. getMonth(): Phương thức này được sử dụng để lấy tháng từ DatePicker. Phương thức này trả về một số nguyên.

Code sau lấy tháng từ DatePicker

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
int month = simpleDatePicker.getMonth(); // Lấy tháng được chọn

4. getYear(): Phương thức này được sử dụng để lấy năm từ DatePicker. Phương thức này trả về một số nguyên.

Code sau lấy năm từ DatePicker

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
int year = simpleDatePicker.getYear(); // Lấy năm được chọn

5. getFirstDayOfWeek(): Phương thức này lấy ngày đầu tiên trong tuần. Phương thức này trả về một số nguyên.

Code sau lấy ngày đầu tiên trong tuần

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker

int firstDay=simpleDatePicker.getFirstDayOfWeek(); // Lấy ngày đầu tiên trong tuần

Một số thuộc tính thường dùng của DatePicker

1. android:id: Là thuộc tính duy nhất của DatePicker.

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker

2. android:datePickerMode: Thuộc tính này thường dùng để thiết lập DatePicker theo chế độ spinner hay calendar. Mặc định là calendar. Để thiết lập chế độ spinner phải sử dụng API từ 21 trở về sau:

Code sau chúng ta thiết lập chế độ spinner cho DatePicker

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner" /> <!-- spinner mode of a date picker -->

3. android:background: Thuộc tính này thiết lập màu nền hoặc image trong thư mục drawable cho DatePicker

Code sau chúng ta thiết lập màu nền, màu đỏ cho DatePicker

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:background="#f00"/> <!-- red color for the background of the date picker -->

Thiết lập màu nên trong java class

DatePicker simpleDatePicker=(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
simpleDatePicker.setBackgroundColor(Color.RED); //  Thiết lập màu nền là màu đỏ

4. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của TimePicker với nội dung nó chứa: left, right, top or bottom. Cũng ví dụ trên bây giờ chúng ta xác định padding=40dp từ mọi phía của DatePicker.

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:padding="40dp"/> <!-- 40dp padding from all the sides of a date picker -->


Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một DatePicker và một Button. Khi người sử dụng chọn ngày  trên DatePicker và click vào Button "Submit" chúng ta sẽ lấy giá trị của DatePicker rồi hiển thị lên Toast. Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml thiết kế giao diện sau:

Bước 1: Tạo một project tên là DatePickerFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng DatePicker Button trong Relative Layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity">

    <DatePicker
        android:id="@+id/simpleDatePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#150"
        android:datePickerMode="spinner" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/simpleDatePicker"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="#150"
        android:text="SUBMIT"
        android:textColor="#fff"
        android:textSize="20sp"
        android:textStyle="bold" />
</RelativeLayout>

Bước 3: Mở app -> src ->MainActivity.java 

Trong bươc này chúng ta khởi tạo DatePicker và Button. Sau đó, thiết lập sự kiện onClickListener() cho Button. Khi người sử dụng click vào Button này chúng ta lấy giá trị  ngày, tháng, năm của DatePicker và hiển thị nó thông qua Toast.

btnSubmit.setOnClickListener(new OnClickListener() {
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		String	day		=	"Ngày: " + simpleDatePicker.getDayOfMonth();
		String	month	=	"\nTháng: " + simpleDatePicker.getMonth();
		String	year	=	"\n Năm:"+simpleDatePicker.getYear();
		Toast.makeText(MainActivity.this, day+month+year, Toast.LENGTH_LONG).show();
				
		}
});

Toàn bộ code của project

package hiepsiit.com.datepicker;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
	DatePicker simpleDatePicker;
    Button btnSubmit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		simpleDatePicker	=	(DatePicker)	findViewById(R.id.simpleDatePicker);
		btnSubmit			=	(Button)		findViewById(R.id.btnSubmit);
		btnSubmit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String	day		=	"Ngày: " + simpleDatePicker.getDayOfMonth();
				String	month	=	"\nTháng: " + simpleDatePicker.getMonth();
				String	year	=	"\n Năm:"+simpleDatePicker.getYear();
				Toast.makeText(MainActivity.this, day+month+year, Toast.LENGTH_LONG).show();
				
			}
		});
	}
	
}

 


Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng:

Sau đó chọn ngày trên DatePicker và click vào button "SUBMIT":


Ví dụ hiển thị dạng DatePickerDialog 

Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có 1 EditText. Khi người sử dụng click vào EditText sẽ hiển thị DatePicker dạng dialog (hộp thoại). Sau đó, sẽ lấy giá trị ngày, tháng, năm khi người sử dụng chọn ngày trên DatePicker.Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml thiết kế giao diện sau:

Bước 1: Tạo một project tên là DatePickerDialogFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng EditText trong  Relative Layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity">

    <EditText
        android:id="@+id/date"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:background="#d4d4d4"
        android:hint="Chọn Ngày ..."
        android:padding="15dp"
        android:textColor="#897"
        android:textColorHint="#090"
        android:textSize="20sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: Mở app -> src ->MainActivity.java

Trong bước này chúng ta khỏi tạo cho EditText, thiết lập sự kiện cho EditText. Khi người sử dụng click vàoEditText sẽ xuất hiện một Dialog DatePicker để người sử dụng chọn ngày. Cuối cùng ngày xuất hiện trên EditText

edtDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// calender class's instance and get current date , month and year from calender
                final Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR); // current year
                int mMonth = c.get(Calendar.MONTH); // current month
                int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
                // date picker dialog
                datePickerDialog  = new DatePickerDialog(MainActivity.this, new OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						// TODO Auto-generated method stub
						edtDate.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
					}
				}, mYear, mMonth, mDay);
                datePickerDialog.show();
			}
		});

Toàn bộ code của project 

package hiepsiit.com.datepickerdialog;
// Chú ý import thư viện này
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;

public class MainActivity extends Activity {
	EditText edtDate;
    DatePickerDialog datePickerDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edtDate = (EditText) findViewById(R.id.edtDate);
	        // perform click event on edit text
		edtDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// calender class's instance and get current date , month and year from calender
                final Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR); // current year
                int mMonth = c.get(Calendar.MONTH); // current month
                int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
                // date picker dialog
                datePickerDialog  = new DatePickerDialog(MainActivity.this, new OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						// TODO Auto-generated method stub
						edtDate.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
					}
				}, mYear, mMonth, mDay);
                datePickerDialog.show();
			}
		});
	}

}

Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng:

Sau đó click vào EditText:

Chọn ngày trên DatePickerDialog, Click Ok