Android DatePickerDialog和TimePickerDialog显示样式
可以用DatePickerDialog显示选取日期的对话框。可以设置显示的样式
1、通过构造方法设置显示样式。
可以通过DatePickerDialog(Context context, int theme, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth)这个构造方法的第二个参数来设置显示样式。
这个theme参数对应的值,可以使用AlertDialog中的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
对于TimePickerDialog而言,它的样式设置,只有构造函数一种方式,对应的theme参数和DatePickerDialog相同。它内部定义了一个TimePicker,但是没有提供获取的方式。
在构造TimePickerDialog和DatePickerDialog的时候最好使用DialogFragment来进行构造。
帮助文档中例子:
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); // Create a new instance of TimePickerDialog and return it return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity())); } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Do something with the time chosen by the user } }
public void showTimePickerDialog(View v) { DialogFragment newFragment = new TimePickerFragment(); newFragment.show(getSupportFragmentManager(), "timePicker"); }
对于DialogFragment可以参考文档: Android 官方推荐 : DialogFragment 创建对话框
DatePickerDialog的OnDateSetListener被调用两次的bug解决方案
使用DatePickerDialog.OnDateSetListener
的时候发现回调了两次。原因貌似源码的问题。
解决方案:
判断下view是否显示着
final Context context = MainActivity.this;
Calendar calendar = Calendar.getInstance();
int y = calendar.get(Calendar.YEAR);
int m = calendar.get(Calendar.MONTH);
int d = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
if (view.isShown()) { // 这里判断
Toast.makeText(context, String.format(Locale.CHINA, "(y, m, d) = (%d, %d, %d)", year, month, dayOfMonth), Toast.LENGTH_SHORT).show();
}
}
};
DatePickerDialog datePickerDialog = new DatePickerDialog(context, onDateSetListener, y, m, d);
datePickerDialog.show();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15