Android 日期和时间选择器

时间:2021-12-15 18:05:54


1. 日期选择器 : 

Calendar calendar = Calendar.getInstance();
new DatePickerDialog(DialogSample.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String info = "您选择的日期是:";
info += year + "年" + monthOfYear + "月" + dayOfMonth + "日";
//dateText.setText(info);
Toast.makeText(DialogSample.this, info, Toast.LENGTH_LONG).show();
}
}, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();



2. 时间选择器 : 

Calendar calendar = Calendar.getInstance();
new TimePickerDialog(DialogSample.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String timeInfo = "您选择的时间是:";
timeInfo += hourOfDay+ "时" + minute + "分";
Toast.makeText(DialogSample.this, timeInfo, Toast.LENGTH_LONG).show();
}
},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();


使用示例 : 

package net.simonvt.datepicker.samples;

import java.util.Calendar;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;


public class DialogSample extends Activity {

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

findViewById(R.id.btnDialog).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*final DatePickDialog dp = new DatePickDialog(DialogSample.this, "日期选择", "确定", "取消");
dp.show();*/
Calendar calendar = Calendar.getInstance();
/*
new DatePickerDialog(DialogSample.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String info = "您选择的日期是:";
info += year + "年" + monthOfYear + "月" + dayOfMonth + "日";
//dateText.setText(info);
Toast.makeText(DialogSample.this, info, Toast.LENGTH_LONG).show();
}
}, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show(); */
new TimePickerDialog(DialogSample.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String timeInfo = "您选择的时间是:";
timeInfo += hourOfDay+ "时" + minute + "分";
Toast.makeText(DialogSample.this, timeInfo, Toast.LENGTH_LONG).show();
}
},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
}
});

}
}