天天看點

筆記8 | 系統時間設定界面DatePickerDialog,TimePickerDialog,DatePicker

位址

筆記8 | 系統時間設定界面DatePickerDialog,TimePickerDialog,DatePicker
最近工作的時候需要設定時間日期月曆等,最終選用的是DatePickerDialog和TimePickerDialog方法來實作,由于還沒自定義布局,直接調用就可以,實作起來挺簡單,現在通過實作和檢視源碼來進行解析;

目錄

  • DatePickerDialog實作和分析
  • TimePickerDialog實作和分析
  • DatePicker實作和分析

DatePickerDialog實作和分析

主要代碼:

  1. int year,month,day,s,f,m;
  2. private void initDataTime() {//擷取時間資訊
  3. Calendar calendar = Calendar.getInstance();
  4. year = calendar.get(Calendar.YEAR); //年
  5. month = calendar.get(Calendar.WEEK_OF_MONTH); //月
  6. day = calendar.get(Calendar.DAY_OF_YEAR); //日
  7. s = calendar.get(Calendar.HOUR_OF_DAY); //時
  8. f = calendar.get(Calendar.MINUTE); //分
  9. m = calendar.get(Calendar.SECOND); //秒
  10. }
  11. DatePickerDialog.OnDateSetListener onDateSetListene = new DatePickerDialog.OnDateSetListener() {
  12. @Override
  13. public void onDateSet(DatePicker view, int year, int monthOfYear,
  14. int dayOfMonth) {
  15. }
  16. };
  1. Button button1= (Button) findViewById(R.id.b01);//打開年月日設定界面
  2. button1.setOnClickListener(new OnClickListener() {
  3. @Override
  4. public void onClick(View v) {
  5. new DatePickerDialog(getApplication(), R.style.AppTheme,onDateSetListene , year,month,day);
  6. }
  7. });

調出系統的時間設定界面即可對系統時間進行設定,簡單明了,我們看看源碼是怎麼實作的:DatePickerDialog.class

  1. /*
  2. * Copyright (C) 2007 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package android.app;
  17. import android.content.Context;
  18. import android.content.DialogInterface;
  19. import android.content.DialogInterface.OnClickListener;
  20. import android.os.Bundle;
  21. import android.text.format.DateUtils;
  22. import android.view.LayoutInflater;
  23. import android.view.View;
  24. import android.widget.DatePicker;
  25. import android.widget.DatePicker.OnDateChangedListener;
  26. import com.android.internal.R;
  27. import java.util.Calendar;
  28. /**
  29. * A simple dialog containing an {@link android.widget.DatePicker}.
  30. *
  31. * <p>See the <a href="{@docRoot}guide/topics/ui/controls/pickers.html" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >Pickers</a>
  32. * guide.</p>
  33. */
  34. public class DatePickerDialog extends AlertDialog implements OnClickListener,
  35. OnDateChangedListener {
  36. private static final String YEAR = "year";
  37. private static final String MONTH = "month";
  38. private static final String DAY = "day";
  39. private final DatePicker mDatePicker; //用于存取動态的時間值
  40. private final OnDateSetListener mCallBack;
  41. private final Calendar mCalendar;
  42. private boolean mTitleNeedsUpdate = true;
  43. /**
  44. * The callback used to indicate the user is done filling in the date.
  45. */
  46. public interface OnDateSetListener {
  47. /**
  48. * @param view The view associated with this listener.
  49. * @param year The year that was set.
  50. * @param monthOfYear The month that was set (0-11) for compatibility
  51. * with {@link java.util.Calendar}.
  52. * @param dayOfMonth The day of the month that was set.
  53. */
  54. void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth);
  55. }
  56. /** 方法 一
  57. * @param context The context the dialog is to run in.
  58. * @param callBack How the parent is notified that the date is set.
  59. * @param year The initial year of the dialog.
  60. * @param monthOfYear The initial month of the dialog.
  61. * @param dayOfMonth The initial day of the dialog.
  62. */
  63. public DatePickerDialog(Context context,
  64. OnDateSetListener callBack, //傳對應的方法進來,通知父節點設定日期
  65. int year, //
  66. int monthOfYear,
  67. int dayOfMonth) {
  68. this(context, 0, callBack, year, monthOfYear, dayOfMonth);
  69. }
  70. /** 方法 二
  71. * @param context The context the dialog is to run in.
  72. * @param theme the theme to apply to this dialog
  73. * @param callBack How the parent is notified that the date is set.
  74. * @param year The initial year of the dialog.
  75. * @param monthOfYear The initial month of the dialog.
  76. * @param dayOfMonth The initial day of the dialog.
  77. * /
  78. public DatePickerDialog(Context context,
  79. int theme, //傳入對應的主題
  80. OnDateSetListener callBack, //傳對應的時間設定方法進來,通知父節點設定日期
  81. int year,
  82. int monthOfYear,
  83. int dayOfMonth) {
  84. super(context, theme);
  85. mCallBack = callBack;
  86. mCalendar = Calendar.getInstance();
  87. Context themeContext = getContext();
  88. setButton(BUTTON_POSITIVE, themeContext.getText(R.string.date_time_done), this);
  89. setIcon(0);
  90. LayoutInflater inflater =
  91. (LayoutInflater) themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  92. View view = inflater.inflate(R.layout.date_picker_dialog, null);
  93. setView(view);
  94. mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
  95. mDatePicker.init(year, monthOfYear, dayOfMonth, this);
  96. updateTitle(year, monthOfYear, dayOfMonth);
  97. }
  98. public void onClick(DialogInterface dialog, int which) {
  99. tryNotifyDateSet();
  100. }
  101. public void onDateChanged(DatePicker view, int year,
  102. int month, int day) {
  103. mDatePicker.init(year, month, day, this);
  104. updateTitle(year, month, day);
  105. }
  106. /**
  107. * Gets the {@link DatePicker} contained in this dialog.
  108. *
  109. * @return The calendar view.
  110. */
  111. public DatePicker getDatePicker() { //首先會拿到目前DatePicker
  112. return mDatePicker;
  113. }
  114. /**
  115. * 設定日期
  116. *
  117. * @param year The date year.
  118. * @param monthOfYear The date month.
  119. * @param dayOfMonth The date day of month.
  120. */
  121. public void updateDate(int year, int monthOfYear, int dayOfMonth) {
  122. mDatePicker.updateDate(year, monthOfYear, dayOfMonth);
  123. }
  124. private void tryNotifyDateSet() {//将動态的時間傳給mCallBack方法
  125. if (mCallBack != null) {
  126. mDatePicker.clearFocus();
  127. mCallBack.onDateSet(mDatePicker, mDatePicker.getYear(),
  128. mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
  129. }
  130. }
  131. @Override
  132. protected void onStop() {
  133. tryNotifyDateSet();
  134. super.onStop();
  135. }
  136. private void updateTitle(int year, int month, int day) {
  137. if (!mDatePicker.getCalendarViewShown()) {
  138. mCalendar.set(Calendar.YEAR, year);
  139. mCalendar.set(Calendar.MONTH, month);
  140. mCalendar.set(Calendar.DAY_OF_MONTH, day);
  141. String title = DateUtils.formatDateTime(mContext,
  142. mCalendar.getTimeInMillis(),
  143. DateUtils.FORMAT_SHOW_DATE
  144. | DateUtils.FORMAT_SHOW_WEEKDAY
  145. | DateUtils.FORMAT_SHOW_YEAR
  146. | DateUtils.FORMAT_ABBREV_MONTH
  147. | DateUtils.FORMAT_ABBREV_WEEKDAY);
  148. setTitle(title);
  149. mTitleNeedsUpdate = true;
  150. } else {
  151. if (mTitleNeedsUpdate) {
  152. mTitleNeedsUpdate = false;
  153. setTitle(R.string.date_picker_dialog_title);
  154. }
  155. }
  156. }
  157. @Override
  158. public Bundle onSaveInstanceState() {
  159. Bundle state = super.onSaveInstanceState();
  160. state.putInt(YEAR, mDatePicker.getYear());
  161. state.putInt(MONTH, mDatePicker.getMonth());
  162. state.putInt(DAY, mDatePicker.getDayOfMonth());
  163. return state;
  164. }
  165. @Override
  166. public void onRestoreInstanceState(Bundle savedInstanceState) {
  167. super.onRestoreInstanceState(savedInstanceState);
  168. int year = savedInstanceState.getInt(YEAR);
  169. int month = savedInstanceState.getInt(MONTH);
  170. int day = savedInstanceState.getInt(DAY);
  171. mDatePicker.init(year, month, day, this);
  172. }
  173. }

TimePickerDialog實作和源碼

  1. TimePickerDialog.OnTimeSetListener onTimeSetListene = new TimePickerDialog.OnTimeSetListener() {
  2. @Override
  3. public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
  4. }
  5. };
  6. ContentResolver cv = this.getContentResolver();
  7. String strTimeFormat = android.provider.Settings.System.getString(cv,
  8. android.provider.Settings.System.TIME_12_24);
  9. public boolean is24(){//判斷是否為24小時制
  10. return strTimeFormat.equals("24");
  11. }
  12. Button button2= (Button) findViewById(R.id.b02);//彈出系統時間界面
  13. button2.setOnClickListener(new OnClickListener() {
  14. @Override
  15. public void onClick(View v) {
  16. new TimePickerDialog(getApplication(), onTimeSetListene, s, f, is24());
  17. }
  18. });

兩個源碼差不多,TimePickerDialog隻是多傳了一個is24hour進來,我就不多做解釋。TimePickerDialog.class源碼

  1. /*
  2. * Copyright (C) 2007 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package android.app;
  17. import com.android.internal.R;
  18. import android.content.Context;
  19. import android.content.DialogInterface;
  20. import android.content.DialogInterface.OnClickListener;
  21. import android.os.Bundle;
  22. import android.view.LayoutInflater;
  23. import android.view.View;
  24. import android.widget.TimePicker;
  25. import android.widget.TimePicker.OnTimeChangedListener;
  26. /**
  27. * A dialog that prompts the user for the time of day using a {@link TimePicker}.
  28. *
  29. * <p>See the <a href="{@docRoot}guide/topics/ui/controls/pickers.html" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >Pickers</a>
  30. * guide.</p>
  31. */
  32. public class TimePickerDialog extends AlertDialog
  33. implements OnClickListener, OnTimeChangedListener {
  34. /**
  35. * The callback interface used to indicate the user is done filling in
  36. * the time (they clicked on the 'Set' button).
  37. */
  38. public interface OnTimeSetListener {
  39. /**
  40. * @param view The view associated with this listener.
  41. * @param hourOfDay The hour that was set.
  42. * @param minute The minute that was set.
  43. */
  44. void onTimeSet(TimePicker view, int hourOfDay, int minute);
  45. }
  46. private static final String HOUR = "hour";
  47. private static final String MINUTE = "minute";
  48. private static final String IS_24_HOUR = "is24hour";
  49. private final TimePicker mTimePicker;
  50. private final OnTimeSetListener mCallback;
  51. int mInitialHourOfDay;
  52. int mInitialMinute;
  53. boolean mIs24HourView;
  54. /**
  55. * @param context Parent.
  56. * @param callBack How parent is notified.
  57. * @param hourOfDay The initial hour.
  58. * @param minute The initial minute.
  59. * @param is24HourView Whether this is a 24 hour view, or AM/PM.
  60. */
  61. public TimePickerDialog(Context context,
  62. OnTimeSetListener callBack,
  63. int hourOfDay, int minute, boolean is24HourView) {
  64. this(context, 0, callBack, hourOfDay, minute, is24HourView);
  65. }
  66. /**
  67. * @param context Parent.
  68. * @param theme the theme to apply to this dialog
  69. * @param callBack How parent is notified.
  70. * @param hourOfDay The initial hour.
  71. * @param minute The initial minute.
  72. * @param is24HourView Whether this is a 24 hour view, or AM/PM.
  73. */
  74. public TimePickerDialog(Context context,
  75. int theme,
  76. OnTimeSetListener callBack,
  77. int hourOfDay, int minute, boolean is24HourView) {
  78. super(context, theme);
  79. mCallback = callBack;
  80. mInitialHourOfDay = hourOfDay;
  81. mInitialMinute = minute;
  82. mIs24HourView = is24HourView;
  83. setIcon(0);
  84. setTitle(R.string.time_picker_dialog_title);
  85. Context themeContext = getContext();
  86. setButton(BUTTON_POSITIVE, themeContext.getText(R.string.date_time_done), this);
  87. LayoutInflater inflater =
  88. (LayoutInflater) themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  89. View view = inflater.inflate(R.layout.time_picker_dialog, null);
  90. setView(view);
  91. mTimePicker = (TimePicker) view.findViewById(R.id.timePicker);
  92. // initialize state
  93. mTimePicker.setIs24HourView(mIs24HourView);
  94. mTimePicker.setCurrentHour(mInitialHourOfDay);
  95. mTimePicker.setCurrentMinute(mInitialMinute);
  96. mTimePicker.setOnTimeChangedListener(this);
  97. }
  98. public void onClick(DialogInterface dialog, int which) {
  99. tryNotifyTimeSet();
  100. }
  101. public void updateTime(int hourOfDay, int minutOfHour) {
  102. mTimePicker.setCurrentHour(hourOfDay);
  103. mTimePicker.setCurrentMinute(minutOfHour);
  104. }
  105. public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
  106. /* do nothing */
  107. }
  108. private void tryNotifyTimeSet() {
  109. if (mCallback != null) {
  110. mTimePicker.clearFocus();
  111. mCallback.onTimeSet(mTimePicker, mTimePicker.getCurrentHour(),
  112. mTimePicker.getCurrentMinute());
  113. }
  114. }
  115. @Override
  116. protected void onStop() {
  117. tryNotifyTimeSet();
  118. super.onStop();
  119. }
  120. @Override
  121. public Bundle onSaveInstanceState() {
  122. Bundle state = super.onSaveInstanceState();
  123. state.putInt(HOUR, mTimePicker.getCurrentHour());
  124. state.putInt(MINUTE, mTimePicker.getCurrentMinute());
  125. state.putBoolean(IS_24_HOUR, mTimePicker.is24HourView());
  126. return state;
  127. }
  128. @Override
  129. public void onRestoreInstanceState(Bundle savedInstanceState) {
  130. super.onRestoreInstanceState(savedInstanceState);
  131. int hour = savedInstanceState.getInt(HOUR);
  132. int minute = savedInstanceState.getInt(MINUTE);
  133. mTimePicker.setIs24HourView(savedInstanceState.getBoolean(IS_24_HOUR));
  134. mTimePicker.setCurrentHour(hour);
  135. mTimePicker.setCurrentMinute(minute);
  136. }
  137. }

DatePicker月曆的調用

  1. <DatePicker
  2. android:id="@+id/textView1"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:text="TextView" />

是的,隻需這麼個玩意就可以調出感覺很高大上的月曆界面,源碼就不貼了,太長,如果要自定義界面的話可以研究一下!```

繼續閱讀