記錄下時間選擇的代碼,以後用到,直接考一考。
int bestContactTime_year = 0, bestContactTime_month = 0, bestContactTime_day = 0, bestContactTime_hour = 0, bestContactTime_minute = 0;
TextView BestContactTime15;//用來顯示時間的TextView
/**
* 點擊選擇時間,先選擇日期,再選擇時間
* 如果已經選擇過時間了,則顯示選擇的時間,否則顯示當前時間
* 這裡的時間格式: 2016/2/8 12:35
* @param v
*/
public void onClick(View v) {
String[] time2 = BestContactTime15.getText().toString().split("/");//2016/2/8 12:35
if (time2.length == 3) {
bestContactTime_year = Integer.parseInt(time2[0]);
bestContactTime_month = Integer.parseInt(time2[1]);
String[] xx = time2[2].split(" ");//8 12:35
if (xx.length == 2) {
bestContactTime_day = Integer.parseInt(xx[0]);
String[] xxTime = xx[1].split(":");//12:35
if (xxTime.length == 2) {
bestContactTime_hour = Integer.parseInt(xxTime[0]);
bestContactTime_minute = Integer.parseInt(xxTime[1]);
}
}
}
hadBestContactDate();
}
private void hadBestContactDate() {
Calendar c = Calendar.getInstance();
int year_temp, month_temp, day_temp;
if (bestContactTime_year == 0 || bestContactTime_month == 0 || bestContactTime_day == 0) {
year_temp = c.get(Calendar.YEAR);
month_temp = c.get(Calendar.MONTH) + 1;
day_temp = c.get(Calendar.DAY_OF_MONTH);
} else {
year_temp = bestContactTime_year;
month_temp = bestContactTime_month;
day_temp = bestContactTime_day;
}
new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int Year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
if (Year > 2099) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
return;
}
if (Year < 2000) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
return;
}
bestContactTime_year = Year;
bestContactTime_month = (monthOfYear + 1);
bestContactTime_day = dayOfMonth;
hadBestContactTime();
// BestContactTime15.setText(Year + "/" + (monthOfYear + 1) + "/" + dayOfMonth);
}
}, year_temp, month_temp - 1, day_temp).show();
}
private void hadBestContactTime() {
Calendar c = Calendar.getInstance();
int hour_temp, minute_temp;
if (bestContactTime_hour == 0 || bestContactTime_minute == 0) {
hour_temp = c.get(Calendar.HOUR_OF_DAY);
minute_temp = c.get(Calendar.MINUTE);
} else {
hour_temp = bestContactTime_hour;
minute_temp = bestContactTime_minute;
}
new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
bestContactTime_hour = hour;
bestContactTime_minute = minute;
BestContactTime15.setText(bestContactTime_year + "/" + bestContactTime_month + "/" + bestContactTime_day + " " + bestContactTime_hour + ":" + bestContactTime_minute);
}
}, hour_temp, minute_temp, true).show();
}
可以用AlertDialog.THEME_HOLO_LIGHT來改變PickerDialog的樣式。