如何在DatePickerDialog中将最后选择的日期用作初始日期

时间:2018-07-16 18:55:09

标签: android android-calendar android-datepicker datepickerdialog

我创建了一个由按钮触发的DatePickerFragment。选择日期后,该日期将显示在TextView中。

DatePickerFragment可以按预期工作,但是每次打开它时,它都会显示当前日期,而不是最后选择的日期。

用例

  1. 用户单击dateBoughtButton按钮
  2. 显示日期选择器并显示当前日期
  3. 用户选择的日期与当前日期不同
  4. 用户单击“确定”
  5. 新日期显示在dateTextView TextView
  6. 用户再次单击dateBoughtButton按钮以选择新日期
  7. 日期选择器显示上一次选择的日期->未执行,而是再次显示了当前日期。

我们将为您提供解决此问题的任何帮助。

这是我的代码

MyActivity.java

// DATE PICKER
    dateBoughtButton = findViewById(R.id.date_bought_button);
    dateTextView = findViewById(R.id.date_bought_text_view);

    // Defining Date Format
    final String format = Settings.System.getString(getContentResolver(), Settings.System.DATE_FORMAT);
    final DateFormat dateFormat;
    if (isEmpty(format)) {
        dateFormat = android.text.format.DateFormat.getMediumDateFormat(getApplicationContext());
    } else {
        dateFormat = new SimpleDateFormat(format);
    }

    // Creating Calendar object
    Calendar selectedDate = Calendar.getInstance();

    // Creating Bundle
    final Bundle args = new Bundle();
        args.putInt("year", selectedDate.get(Calendar.YEAR));
        args.putInt("month", selectedDate.get(Calendar.MONTH));
        args.putInt("day", selectedDate.get(Calendar.DAY_OF_MONTH));

    dateBoughtButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerFragment newFragment = new DatePickerFragment();
            newFragment.setArguments(args);
            newFragment.show(getFragmentManager(), "date picker");
            newFragment.setCallBack(onDate);

        }

        DatePickerDialog.OnDateSetListener onDate = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                dateTextView.setText(dateFormat.format(newDate.getTime()));

            }
        };
    });

DatePickerFragment.java

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
DatePickerDialog.OnDateSetListener onDateSet;
int year, month, day;


@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), onDateSet, year, month, day);
}

public void setCallBack(DatePickerDialog.OnDateSetListener onDate) {
    onDateSet = onDate;
}

@Override
public void setArguments(Bundle args) {
    super.setArguments(args);
    year = args.getInt("year");
    month = args.getInt("month");
    day = args.getInt("day");
}

}

0 个答案:

没有答案