Android: get DatePickerDialog in a fragment

2019-05-11 11:06发布

Previously i was using showDialog() which now is deprecated.

I am already in a Fragment which contains an EditText. How can i call this DatePickerDialog and set the EditText's Text to the selected date?

Using DialogFragment seems a bit complicated.

Thank You

2条回答
再贱就再见
2楼-- · 2019-05-11 11:35
啃猪蹄的小仙女
3楼-- · 2019-05-11 11:53

Its easy:

DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year,
            int monthOfYear, int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        updateDisplay();
    }
};

DatePickerDialog d = new DatePickerDialog(getActivity(),
        R.style.MyThemee, mDateSetListener, mYear, mMonth, mDay);
d.show();

UpdateDisplay method:

private void updateDisplay() {

    GregorianCalendar c = new GregorianCalendar(mYear, mMonth, mDay);
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");

    editDate.setText(sdf.format(c.getTime()));

    sdf = new SimpleDateFormat("yyyy-MM-dd");

    transDateString=sdf.format(c.getTime());
}// updateDisplay
查看更多
登录 后发表回答