如何在DatePickerFragment对话框中创建以前选择的日期作为编辑时的默认日期?

时间:2015-09-17 03:09:23

标签: android date android-datepicker

我有一个DatePickerFragment,它启动一个对话框供用户选择日期。该对话框使用今天的日期作为默认日期。一旦用户选择日期,代码就会更新布局中的EditText行。如果用户稍后返回EditText行编辑日期,我希望对话框为先前选择的日期,而不是默认日期,即今天的日期。我读过onPrepareDialog()已弃用,所以不想使用它。我基本上需要存储用户最初设置的年,月和日,然后在对话框第二次显示时使用它们,而不是今天的日期。

partial Fragment file:
...
import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

private EditText txtDate;
private Calendar cal;
private int currentyear;
private int currentmonth;
private int currentday;
private String stringDueDateFrag;

public DatePickerFragment() {
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // Use the current date as the default date that we get from a Calendar object, in the DatePicker Dialog.
    final Calendar cal = Calendar.getInstance();
    currentyear = cal.get(Calendar.YEAR);
    currentmonth = cal.get(Calendar.MONTH);
    currentday = cal.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog dialog = new DatePickerDialog(getActivity(),this,currentyear,currentmonth,currentday);

    return dialog;
}


    txtDate = (EditText) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.FEditText);
    stringDueDateFrag = (month + 1) + "/" + day + "/" + year + " ";
    txtDate.setText(stringDueDateFrag);
    txtDate.setSelection(txtDate.getText().length());
}

1 个答案:

答案 0 :(得分:0)

onCreate()方法中,每次初始化当前日期时,每次调用时都应将日期从EditText传递到DialogFragment

类似的参考问题

Set date of datepickerdialog from EditText