本文共 2439 字,大约阅读时间需要 8 分钟。
Android 提供了time picker 和 data picker可以让用户选择有效的时间和日期. 可以使用DialogFragment 来显示一个TimePickerDialog。这样的话,必须实现DialogFragment 的子类,然后在fragment的onCreateDialog()中返回TimePickerDialog。其次必须要实现TimePickerDialog.OntimeSetListner 来得到用户设定的当前时间. 下面是一个例子: 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 } } 实现DialogFragment的子类后。就可以直接调用DialogFragment的show()方法来显示。 下面这个例子,我们定义一个button 按键,当用户点击这个按键是,我们就显示TimePicker。 <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pick_time" android:onClick="showTimePickerDialog" /> button的回调函数是showTimePickerDialog public void showTimePickerDialog(View v) { DialogFragment newFragment = new TimePickerFragment(); newFragment.show(getSupportFragmentManager(), "timePicker"); } 日期picker完全类似timer picker。也是要实现DialogFragment,但是在onCreateDialog中new一个DatePickerDialog。 public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user } } 也是定义一个button来显示datepicker <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pick_date" android:onClick="showDatePickerDialog" /> button的回调函数是showDatePickerDialog public void showDatePickerDialog(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); }转载地址:http://utcmi.baihongyu.com/