不管我們使用的是什么系統,都需要使用日期和時間,Android同樣也需要創建日期或時間選擇窗口中彈出對話框,下面武林技術頻道小編和大家分享Android日期和時間選擇器實現代碼。
抽出來了一個方法來選擇時間(這里自己規定的只能選擇當前時間以后的日期),日期選擇完畢就會自動彈出時間選擇器讓選擇時間。
/** * 選擇日期和時間 */ private void selectDataAndTime() { // 獲取當前時間 final Calendar calendar = Calendar.getInstance(); /* * toast("當前時間是:" + calendar.get(Calendar.YEAR) + "," + * calendar.get(Calendar.MONTH) + "," + * calendar.get(Calendar.DAY_OF_MONTH)); */ // 日期選擇對話框 dataPickerDialog = new DatePickerDialog(this, new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { // 判斷用戶選擇的日期是否合法 if (calendar.get(Calendar.YEAR) > year) { toast("時間有誤,請從新選擇"); return; } else if (calendar.get(Calendar.YEAR) == year) { if (calendar.get(Calendar.MONTH) > month) { toast("時間有誤,請從新選擇"); return; } else if (calendar.get(Calendar.MONTH) == month) { if (calendar.get(Calendar.DAY_OF_MONTH) > day) { toast("時間有誤,請從新選擇"); return; } else { strDate = year + "-" + (month + 1) + "-" + day; if (timePickerDialog != null) { timePickerDialog.show(); } } } else { strDate = year + "-" + (month + 1) + "-" + day; if (timePickerDialog != null) { timePickerDialog.show(); } } } else { strDate = year + "-" + (month + 1) + "-" + day; if (timePickerDialog != null) { timePickerDialog.show(); } } } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar .get(Calendar.DAY_OF_MONTH)); // 時間選擇對話框 timePickerDialog = new TimePickerDialog(this, new OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hour, int minute) { strTime = strDate + " " + hour + ":" + minute; timeTt.setText(strTime); } }, calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), true); }以上就是武林技術頻道小編為大家帶來的Android日期和時間選擇器實現代碼,相信通過上述介紹,你對這方面知識都有了更多的了解。
新聞熱點
疑難解答