从今天起的前几天打开日期选择器对话框,以选择出生日期

时间:2015-04-15 12:06:45

标签: android

我想打开日期选择器对话框,显示从今天开始的上一个日期。因为我必须选择出生日期。 这不会显示即将到来的日,月和年。

这在Android中是否可行?

2 个答案:

答案 0 :(得分:0)

public 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();
            c.add(Calendar.DAY_OF_MONTH, -1);
            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
            DatePickerDialog dp = new DatePickerDialog(getActivity(), this, year, month, day);
            dp.getDatePicker().setMaxDate(System.currentTimeMillis()-(24*60*60*1000));
            return dp;
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
        }
    }

显示日期选择器:

public void showDatePickerDialog() {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

有关详细信息,请访问:http://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker

答案 1 :(得分:0)

技巧:

final Calendar calendar = Calendar.getInstance();
    try {
        calendar.add(Calendar.DAY_OF_MONTH, -1);//show previous date from today 
        DatePickerDialog dialog = new DatePickerDialog(this,
                new OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) {
                        // TODO Auto-generated method stub
                        calendar.set(Calendar.YEAR, year);
                        calendar.set(Calendar.MONTH, monthOfYear);
                        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        tv.setText(formatDate(calendar.getTime()));
                    }
                }, calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }