android通过DialogFragment实现时间选择

  在android开发中,时间控件是不可或缺的一部分,特别是在设置个人生日或按时间进行搜索时都要用到。Android有内置的DatePicker和timePicker,使用起来也是相当的方便,既可以在布局中添加后findViewById调用,也可以直接在activity中重写onCreateDialog(int id)方法后调用showDialog(int id)弹出,现在网上关于android时间控件的demo也大都基于这两个控件的使用说明。但用过这两个控件的人都知道,这两个时间选择框有两个不太好的地方:1、不是特别美观2、时间控件生命周期不可控。如果想解决上面的问题,我们一般都会通过继承Dialog,写一个美观并且满足要求的时间控件。但这样花费的时间肯定比使用DatePicker和timePicker要多得多。

  当然,网上还是有很多不错的开源时间控件供我们选择,如android-wheel,它是一个仿IOS滚轮样式的时间选择控件(地址:https://github.com/maarek/android-wheel),效果图如下:

  android-spinnerwheel也是一个比错的时间选择控件(地址:https://github.com/ai212983/android-spinnerwheel),效果图如下:

 

  用过datePicker和timepicker的人应该都知道showDialog(int id)其实是一个已经过时的方法,在方法的说明中我们可以找到这么一段话:This method was deprecated in API level 13.Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

  大概意思是:showDialog(int id)这个方法在API 13就已经过时了,新API可以通过使用DialogFragment类和FragmentManager代替它,DailogFragment和FragmentManager在版本API(低于13)也是可用的,但是需要引入兼容包。

  那下面我们来看看怎么通过DialogFragment和FragmentManager来实现选择时间,以及它相对于showDialog(int id)有哪些优势?

  我们首先去android开发者官网找,其中官网就有这么一句话: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可以让我们自己去管理时间选择控件的生命周期并且可以让我们自己给控件设置不同的配置参数,即可以让控件以基本形状显示,也可以放到一个布局中包裹着显示在大屏幕手机上。

  同样,官网上DialogFragment的使用也是很方便的。下面我们来看看:

  首先,我们要自定义个Fragement并让他它继承DialogFragment,还需要让它实现TimePickerDialog.OnTimeSetListener

接口,代码如下:

  

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{

	int _year=1970;
	int _month=0;
	int _day=0;
	
	@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) {
		// TODO 日期选择完成事件,取消时不会触发
		_year=year;
		_month=monthOfYear+1;
		_day=dayOfMonth;
		Log.i(Constant.LOG_TAG, "year="+year+",monthOfYear="+monthOfYear+",dayOfMonth="+dayOfMonth);
	}

	private String getValue(){
		return ""+_year+_month+_day;
	}
	
}

  当我们点击某个控件后要弹出时间选择器只要直接调用下面的方法就行了。

private void showDatePickerFragemnt(){
	DialogFragment fragment=new DatePickerFragment();
	fragment.show(getSupportFragmentManager(), "datePicker");
}

  需要我们注意的是,你的activity是需要继承FragmentActivity或ActionBarActivity的,不然无法获得FragmentManager。

  更多DialogFragment使用说明地址,大家可以去http://developer.android.com/guide/topics/ui/controls/pickers.html

原文地址:https://www.cnblogs.com/xiaoyang2009/p/3721098.html