时间日期选择器、对话框

时间:2021-07-21 23:00:13
public class MainActivity extends ActionBarActivity {
private Context mContext;

private TimePicker timePicker;
private DatePicker datePicker;

private Button btn_date;
private Button btn_time;

private int year;
private int month;
private int day;
private int hour;
private int minute;
private int second;

private String date;
private String time;

private Formatter fmt;
private Calendar cal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mContext = this;

cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR_OF_DAY);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);

fmt = new Formatter();
fmt.format("%d/%d/%d",year,month,day);
date = fmt.toString();
fmt = new Formatter();
fmt.format("%d:%d:%d", hour, minute, second);
time = fmt.toString();


changeDate();

datePicker = (DatePicker)findViewById(R.id.datePicker);
timePicker = (TimePicker)findViewById(R.id.timePicker);

datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
fmt = new Formatter();
fmt.format("%d/%d/%d",year,(monthOfYear+1),dayOfMonth); //month从0开始 所以需要加1
date = fmt.toString();
changeDate();
}
});

timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
fmt = new Formatter();
fmt.format("%d:%d",hourOfDay,minute);
time = fmt.toString();
changeDate();
}
});




//时间 日期 对话框

btn_date = (Button)findViewById(R.id.btn_date);
btn_time = (Button)findViewById(R.id.btn_time);

//日期选择器
btn_date.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
fmt = new Formatter();
fmt.format("%d/%d/%d",year,(monthOfYear+1),dayOfMonth); //month从0开始 所以需要加1
date = fmt.toString();
changeDate();
}
},cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH)).show();
}
});

//时间选择器
btn_time.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new TimePickerDialog(mContext, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
fmt = new Formatter();
fmt.format("%d:%d",hourOfDay,minute);
time = fmt.toString();
changeDate();
}
},cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),true).show();
}
});
}

private void changeDate(){
setTitle(date + " " +time);
}
}

时间日期选择器、对话框
时间日期选择器、对话框