弹出DatePickerDialog对话框的操作…

来源:互联网 发布:车载导航软件哪个最好 编辑:程序博客网 时间:2024/06/15 20:39

今天在写一个小应用的时候,要用到单击文本框实现弹出DatePickerDialog对话框的功能,本想使用showDialog()的方法,但是官方文档说是已经弃用这个方法了,推荐使用DialogFragmet类来实现这个对话框。现在讲讲我是如何实现这个功能的。

  1. 首先编写一个类用来存放年、月、日。

public class Datepicker {
private int year;
private int month;
private int day;

并实现该类的构造方法和Getters和Setters方法。

   2. 编写一个类,该类继承DialogFragment,并实现OnDateSetListener接口。在onCreateDialog(BundlesavedInstanceState)方法中,实现刚刚创建日期选择框所确定的年月日为当前的年月日,并返回DatePickerDialog对象,代码如下:

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 newDatePickerDialog(getActivity(), this, year, month, day);

        在onDateSet(DatePicker view, int year, intmonthOfYear,  intdayOfMonth)方法中,设置年月日,代码如下:

datepicker.setYear(year);
  datepicker.setMonth(monthOfYear);
  datepicker.setDay(dayOfMonth);

3.  最后通过传入构造参数的EditText控件,将datepicker中的年月日设置为文本。

 

0 0