CSDN 地址:http://blog.csdn.net/xiangyong_1521/article/details/77952320
最近工作的时候需要设置时间日期日历等,最终选用的是DatePickerDialog和TimePickerDialog方法来实现,由于还没自定义布局,直接调用就可以,实现起来挺简单,现在通过实现和查看源码来进行实现分析;
主要代码:
int year,month,day,s,f,m;
private void initDataTime() {//获取时间信息
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR); //年
month = calendar.get(Calendar.WEEK_OF_MONTH); //月
day = calendar.get(Calendar.DAY_OF_YEAR); //日
s = calendar.get(Calendar.HOUR_OF_DAY); //时
f = calendar.get(Calendar.MINUTE); //分
m = calendar.get(Calendar.SECOND); //秒
}
DatePickerDialog.OnDateSetListener onDateSetListene = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
}
};
Button button1= (Button) findViewById(R.id.b01);//打开年月日设置界面
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(getApplication(), R.style.AppTheme,onDateSetListene , year,month,day);
}
});
调出系统的时间设置界面即可对系统时间进行设置,简单明了,我们看看源码是怎么实现的: DatePickerDialog.class
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import com.android.internal.R;
import java.util.Calendar;
/**
* A simple dialog containing an {@link android.widget.DatePicker}.
*
* <p>See the <a href="{@docRoot}guide/topics/ui/controls/pickers.html">Pickers</a>
* guide.</p>
*/
public class DatePickerDialog extends AlertDialog implements OnClickListener,
OnDateChangedListener {
private static final String YEAR = "year";
private static final String MONTH = "month";
private static final String DAY = "day";
private final DatePicker mDatePicker; //用于存取动态的时间值
private final OnDateSetListener mCallBack;
private final Calendar mCalendar;
private boolean mTitleNeedsUpdate = true;
/**
* The callback used to indicate the user is done filling in the date.
*/
public interface OnDateSetListener {
/**
* @param view The view associated with this listener.
* @param year The year that was set.
* @param monthOfYear The month that was set (0-11) for compatibility
* with {@link java.util.Calendar}.
* @param dayOfMonth The day of the month that was set.
*/
void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth);
}
/** 方法 一
* @param context The context the dialog is to run in.
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog.
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
*/
public DatePickerDialog(Context context,
OnDateSetListener callBack, //传对应的方法进来,通知父节点设置日期
int year, //
int monthOfYear,
int dayOfMonth) {
this(context, 0, callBack, year, monthOfYear, dayOfMonth);
}
/** 方法 二
* @param context The context the dialog is to run in.
* @param theme the theme to apply to this dialog
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog.
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
** /
public DatePickerDialog(Context context,
int theme, //传入对应的主题
OnDateSetListener callBack, //传对应的时间设置方法进来,通知父节点设置日期
int year,
int monthOfYear,
int dayOfMonth) {
super(context, theme);
mCallBack = callBack;
mCalendar = Calendar.getInstance();
Context themeContext = getContext();
setButton(BUTTON_POSITIVE, themeContext.getText(R.string.date_time_done), this);
setIcon(0);
LayoutInflater inflater =
(LayoutInflater) themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.date_picker_dialog, null);
setView(view);
mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
mDatePicker.init(year, monthOfYear, dayOfMonth, this);
updateTitle(year, monthOfYear, dayOfMonth);
}
public void onClick(DialogInterface dialog, int which) {
tryNotifyDateSet();
}
public void onDateChanged(DatePicker view, int year,
int month, int day) {
mDatePicker.init(year, month, day, this);
updateTitle(year, month, day);
}
/**
* Gets the {@link DatePicker} contained in this dialog.
*
* @return The calendar view.
*/
public DatePicker getDatePicker() { //首先会拿到当前DatePicker
return mDatePicker;
}
/**
* 设置日期
*
* @param year The date year.
* @param monthOfYear The date month.
* @param dayOfMonth The date day of month.
*/
public void updateDate(int year, int monthOfYear, int dayOfMonth) {
mDatePicker.updateDate(year, monthOfYear, dayOfMonth);
}
private void tryNotifyDateSet() {//将动态的时间传给mCallBack方法
if (mCallBack != null) {
mDatePicker.clearFocus();
mCallBack.onDateSet(mDatePicker, mDatePicker.getYear(),
mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
}
}
@Override
protected void onStop() {
tryNotifyDateSet();
super.onStop();
}
private void updateTitle(int year, int month, int day) {
if (!mDatePicker.getCalendarViewShown()) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.DAY_OF_MONTH, day);
String title = DateUtils.formatDateTime(mContext,
mCalendar.getTimeInMillis(),
DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_YEAR
| DateUtils.FORMAT_ABBREV_MONTH
| DateUtils.FORMAT_ABBREV_WEEKDAY);
setTitle(title);
mTitleNeedsUpdate = true;
} else {
if (mTitleNeedsUpdate) {
mTitleNeedsUpdate = false;
setTitle(R.string.date_picker_dialog_title);
}
}
}
@Override
public Bundle onSaveInstanceState() {
Bundle state = super.onSaveInstanceState();
state.putInt(YEAR, mDatePicker.getYear());
state.putInt(MONTH, mDatePicker.getMonth());
state.putInt(DAY, mDatePicker.getDayOfMonth());
return state;
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
int year = savedInstanceState.getInt(YEAR);
int month = savedInstanceState.getInt(MONTH);
int day = savedInstanceState.getInt(DAY);
mDatePicker.init(year, month, day, this);
}
}
TimePickerDialog.OnTimeSetListener onTimeSetListene = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
}
}; ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,android
.provider.Settings.System.TIME_12_24);
public boolean is24(){//判断是否为24小时制
return strTimeFormat.equals("24");
}
Button button2= (Button) findViewById(R.id.b02);//弹出系统时间界面
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new TimePickerDialog(getApplication(), onTimeSetListene, s, f, is24());
}
});
两个源码差不多,TimePickerDialog只是多传了一个is24hour进来,懂得如何运行的就可以。 TimePickerDialog.class源码
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app;
import com.android.internal.R;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
/**
* A dialog that prompts the user for the time of day using a {@link TimePicker}.
*
* <p>See the <a href="{@docRoot}guide/topics/ui/controls/pickers.html">Pickers</a>
* guide.</p>
*/
public class TimePickerDialog extends AlertDialog
implements OnClickListener, OnTimeChangedListener {
/**
* The callback interface used to indicate the user is done filling in
* the time (they clicked on the 'Set' button).
*/
public interface OnTimeSetListener {
/**
* @param view The view associated with this listener.
* @param hourOfDay The hour that was set.
* @param minute The minute that was set.
*/
void onTimeSet(TimePicker view, int hourOfDay, int minute);
}
private static final String HOUR = "hour";
private static final String MINUTE = "minute";
private static final String IS_24_HOUR = "is24hour";
private final TimePicker mTimePicker;
private final OnTimeSetListener mCallback;
int mInitialHourOfDay;
int mInitialMinute;
boolean mIs24HourView;
/**
* @param context Parent.
* @param callBack How parent is notified.
* @param hourOfDay The initial hour.
* @param minute The initial minute.
* @param is24HourView Whether this is a 24 hour view, or AM/PM.
*/
public TimePickerDialog(Context context,
OnTimeSetListener callBack,
int hourOfDay, int minute, boolean is24HourView) {
this(context, 0, callBack, hourOfDay, minute, is24HourView);
}
/**
* @param context Parent.
* @param theme the theme to apply to this dialog
* @param callBack How parent is notified.
* @param hourOfDay The initial hour.
* @param minute The initial minute.
* @param is24HourView Whether this is a 24 hour view, or AM/PM.
*/
public TimePickerDialog(Context context,
int theme,
OnTimeSetListener callBack,
int hourOfDay, int minute, boolean is24HourView) {
super(context, theme);
mCallback = callBack;
mInitialHourOfDay = hourOfDay;
mInitialMinute = minute;
mIs24HourView = is24HourView;
setIcon(0);
setTitle(R.string.time_picker_dialog_title);
Context themeContext = getContext();
setButton(BUTTON_POSITIVE, themeContext.getText(R.string.date_time_done), this);
LayoutInflater inflater =
(LayoutInflater) themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.time_picker_dialog, null);
setView(view);
mTimePicker = (TimePicker) view.findViewById(R.id.timePicker);
// initialize state
mTimePicker.setIs24HourView(mIs24HourView);
mTimePicker.setCurrentHour(mInitialHourOfDay);
mTimePicker.setCurrentMinute(mInitialMinute);
mTimePicker.setOnTimeChangedListener(this);
}
public void onClick(DialogInterface dialog, int which) {
tryNotifyTimeSet();
}
public void updateTime(int hourOfDay, int minutOfHour) {
mTimePicker.setCurrentHour(hourOfDay);
mTimePicker.setCurrentMinute(minutOfHour);
}
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
/* do nothing */
}
private void tryNotifyTimeSet() {
if (mCallback != null) {
mTimePicker.clearFocus();
mCallback.onTimeSet(mTimePicker, mTimePicker.getCurrentHour(),
mTimePicker.getCurrentMinute());
}
}
@Override
protected void onStop() {
tryNotifyTimeSet();
super.onStop();
}
@Override
public Bundle onSaveInstanceState() {
Bundle state = super.onSaveInstanceState();
state.putInt(HOUR, mTimePicker.getCurrentHour());
state.putInt(MINUTE, mTimePicker.getCurrentMinute());
state.putBoolean(IS_24_HOUR, mTimePicker.is24HourView());
return state;
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
int hour = savedInstanceState.getInt(HOUR);
int minute = savedInstanceState.getInt(MINUTE);
mTimePicker.setIs24HourView(savedInstanceState.getBoolean(IS_24_HOUR));
mTimePicker.setCurrentHour(hour);
mTimePicker.setCurrentMinute(minute);
}
}
<DatePicker
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView" />
是的,只需这么个玩意就可以调出感觉很高大上的日历界面,源码就不贴了,太长,如果要自定义界面的话可以研究一下! ```
Theme的显示样式
AlertDialog.THEME_TRADITIONAL
AlertDialog.THEME_HOLO_DARK
AlertDialog.THEME_HOLO_LIGHT
AlertDialog.THEME_DEVICE_DEFAULT_DARK
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT
2、通过DatePicker设置显示样式
首先获取DatePicker,然后使用DatePicker.setCalendarViewShow(boolean)和DatePicker.setSpinnersShow(boolean)来设置。
CalendarView和Spinners的值分别为true和false
CalendarView和Spinners的值分别为false和true
CalendarView和Spinners的值都是false
CalendarView和Spinners的值都是true