android 对话框(三)DatePickerDialog和TimePickerDialog

时间:2022-11-01 17:15:31
时间和日期控件在app中的应用很常见,我们看下面的一段话:
We recommend that you use DialogFragment to host each time or date picker. The DialogFragment manages the dialog lifecycle for you and allows you to display the pickers in different layout configurations, such as in a basic dialog on handsets or as an embedded part of the layout on large screens.
官方推荐用DialogFragment做为时间或日期的宿主,这做的做的好处是可以根据不同的布局配置生显示不同的样式,在手机中可以作为一个弹出框在大屏幕中可以作为布局的一部分。
1.创建一个时间选择器  创建一个Fragment类继承DialogFragment,  实现onCreateDialog()方法返回一个TimePickerDialog实例  实现TimePickerDialog.OnTimeSetListener的接口,用于监听用户时间的选择
package com.wuhr.com.dialogbgtransparent;  import android.app.Dialog;import android.app.TimePickerDialog;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.v4.app.DialogFragment;import android.widget.TimePicker; import java.text.DateFormat;import java.util.Calendar;import java.util.Date; /** * Created by wuhr_pc on 2016-3-11. */public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(),this,hour,minute, android.text.format.DateFormat.is24HourFormat(getActivity())); }  @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  }}
在主Activity调用显示时间选择器
 DialogFragment dateDialog=new DatePickerFragment(); dateDialog.show(getSupportFragmentManager(),"timeDialog"); 
2.日期选择器,原理根时间选择器是一样的。
package com.wuhr.com.dialogbgtransparent;  import android.app.DatePickerDialog;import android.app.Dialog;import android.app.TimePickerDialog;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.v4.app.DialogFragment;import android.widget.DatePicker;import android.widget.TimePicker; import java.util.Calendar; /** * Created by wuhr_pc on 2016-3-11. */public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { 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); return new DatePickerDialog(getActivity(),this,year,month,day);}  @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {  }}
在主Activity调用显示日期选择器
 DialogFragment dateDialog=new DatePickerFragment(); dateDialog.show(getSupportFragmentManager(),"dateDialog");
上张效果图android 对话框(三)DatePickerDialog和TimePickerDialog
android 对话框(三)DatePickerDialog和TimePickerDialog