How do I show the previously selected date in a DatePickerDialog on next call?

三世轮回 提交于 2021-02-08 15:07:38

问题


A DatePickerDialog is loaded in a Fragment with today's showing as the default date when the dialog is first opened. The user then selects a date and then the dialog is dismissed. On next re-open, how do I show the previously selected date as the default date rather than it showing today's date?

I have tried .set() in the Activity but don't know how to use .get() to retrieve the date in the fragment. I've tried an interface with a listener between the Activity and the fragement but could not get that to work and it seems overly complicated for the simple task I am trying to achieve. And I've tried a bundle sent from the Activity to the fragment but I haven't been able to get that to work either. Please advise.

Activity file:

...
final Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

Fragment file:

...
public static 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();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Save selected date in a date variable here?  How?
    // How do I then use the date variable in onCreateDialog
    // rather than the get(Calendar) code that returns today's date? 
}

}


回答1:


Get a DatePicker with default today date:

@SuppressLint("SimpleDateFormat")
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private Calendar calendar = null;

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
OnDateSetListener dateSetListener = new OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(year, monthOfYear, dayOfMonth);
//this line save-s the DatePicker selected date to the edittext
//you can try with:  Date dpDate =new Date(sdf.format(calendar.getTime();
birthDate.setText(sdf.format(calendar.getTime()));
}
};

final DatePickerFragment datePickerFragment = new DatePickerFragment(StepSettingsView.this, dateSetListener, year, month, day);
datePickerFragment.getDatePicker().setMaxDate(new Date().getTime());
datePickerFragment.show();
                    datePickerFragment.getButton(DatePickerDialog.BUTTON_NEUTRAL).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
birthDate.setText("");
datePickerFragment.dismiss();
}
});



回答2:


In Bundle you should send the year month and day value and retreive here like:

@Override
public Dialog onCreateDialog(Bundle mBundle) {

    int year = mBundle.getInt("YEAR");
    int month =  mBundle.getInt("MONTH");
    int day =  mBundle.getInt("DAY");

    return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Save selected date in a date variable here?  How?
    // How do I then use the date variable in onCreateDialog
    // rather than the get(Calendar) code that returns today's date? 
}

From where we are calling this date time picker fragment from there you need to send this bundle.




回答3:


Declare Globally

private DatePicker datepicker;

Copy and paste below function

   private void selectDate() {

    final DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
            new DatePickerDialog.OnDateSetListener() {

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

                    datepicker = new DatePicker(getActivity());

                    datepicker.init(year, monthOfYear + 1, dayOfMonth, null);


                }
            }, mYear, mMonth, mDay);

    if (datepicker != null) {
        datePickerDialog.updateDate(datepicker.getYear(), datepicker.getMonth() - 1, datepicker.getDayOfMonth());

    }
    datePickerDialog.show();
}



回答4:


if i follow you question than put the date in sharedPreferences on

public void onDateSet(DatePicker view, int year, int month, int day) {
// here put you date to shared preference in get later//
// you can convert it to time stamp and easily save
}

By using sharedPreferences you can set any where and get any where in your application.




回答5:


Please get this

private String lastStoredDate;


    if(lastStoredDate == null || lastStoredDate.trim().length() == 0){
        lastStoredDate = getCurrentDate("MM/dd/yyyy");
    }
    String dobSplit[] = lastStoredDate.split("/");
    Calendar calendar = Calendar.getInstance();
    calendar.set(Integer.parseInt(dobSplit[2]), Integer.parseInt(dobSplit[0]), Integer.parseInt(dobSplit[1]));
    int iDay=calendar.get(Calendar.DATE);
    int iMonth=calendar.get(Calendar.MONTH)-1;
    int iYear=calendar.get(Calendar.YEAR);
    DatePickerDialog dbDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            StringBuilder date = new StringBuilder();

            monthOfYear = monthOfYear + 1;
            if (monthOfYear < 10) {
                date.append("0"+monthOfYear+"/"+dayOfMonth);
            }else{
                date.append(monthOfYear).append("/"+dayOfMonth);
            }
            date.append("/"+year);
          lastStoredDate = date.toString();
        }
    },iYear,iMonth,iDay);
    dbDialog.getDatePicker().setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);

    dbDialog.show();

// To get currrent date

    public static String getCurrentDate(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    String formattedDate = sdf.format(Calendar.getInstance().getTime());
    return formattedDate;
    }



回答6:


First of all this code is working on `edittext` or any button to set previous and current date in to Date picker.                

public class AboutMeActivity extends AppCompatActivity {

DatePickerDialog datePickerDialog;
private TextInputEditText   edtDateOfBirth;
private int mYear;
private int mMonth;
private int mDay;

private  View.OnClickListener edtDateOfBirthClickListener    =   new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        datePickerDialog = new DatePickerDialog(AboutMeActivity.this, new DatePickerDialog.OnDateSetListener() { 

       @Override
       public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

          //here i=year,i1= month,i2=days.

            mYear =i;
            mMonth=i1;
            mDay=i2;

            edtDateOfBirth.setText(i2 + "-" + (i1 + 1) + "-" + i);
       }

    }, mYear, mMonth, mDay);

   datePickerDialog.show();
 }};                     

  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);            
       edtDateOfBirth = (TextInputEditText)findViewById(R.id.edtDateOfBirth);     if(edtDateOfBirth!=null)edtDateOfBirth.setOnClickListener(edtDateOfBirthClickListener);  

  Calendar c = Calendar.getInstance();
  mYear = c.get(Calendar.YEAR); // current year
  mMonth = c.get(Calendar.MONTH); // current month
  mDay = c.get(Calendar.DAY_OF_MONTH); //current Day.       

}

}



回答7:


My Edit text field displays the current date and updates the last selected date when the Datepicker Dailog as opens next time by fetching the values from the edit text field and updating the Date picker dialog.

I have a very detailed explanation of the on click function that I have set on the Edit text field.

I have posted the entire function as you can see from the comments which parts can be used for your problem

Note: I am not catching null values as I am displaying current date by default in my edit text view.

  public void setDateDialog(View view) {
    // Edit text field which on click opens the Datepicker Dialog
    final EditText eText = findViewById(R.id.timeField);
    // Get the current value in the edit text field
    String userInput = eText.getText().toString();
    // Remove the date seprators
    String[] dateParts = userInput.split("/");
    // Day String
    String dayStr = dateParts[0];
    // Month String
    String monthStr = dateParts[1];
    // Year String
    String yearStr = dateParts[2];
    // Day String to integer
    final int dayInt = Integer.parseInt(dayStr);
    // Month String to integer ( Substarct 1 as month as count starts from 0)
    final int monthInt = Integer.parseInt(monthStr)-1;
    // Year String to integer
    final int yearInt  = Integer.parseInt(yearStr);
    // Initialise the calender
    final Calendar cldr = Calendar.getInstance();
    int day = cldr.get(Calendar.DATE);
    int month = cldr.get(Calendar.MONTH);
    int year = cldr.get(Calendar.YEAR);

    DatePickerDialog pickerDialog = new DatePickerDialog(QuickLaunch.this, R.style.DatePickerTheme, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
           // Adding Zero before month if month is single digit
            int month = monthOfYear + 1;
            String fm = "" + month;
            String fd = "" + dayOfMonth;
            if (month < 10) {
                fm = "0" + month;
            }
            if (dayOfMonth < 10) {
                fd = "0" + dayOfMonth;
            }
            eText.setText(fd + "/" + (fm) + "/" + year);
        }
    }, year, month, day);
    // Set the maximum date till tommorrow
    pickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 1));
    // Set the minimun date till yesterday
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 1));
    //Set the previous date in datepicker
    pickerDialog.getDatePicker().init(yearInt,monthInt,dayInt,null);
    pickerDialog.show();
}


来源:https://stackoverflow.com/questions/32710585/how-do-i-show-the-previously-selected-date-in-a-datepickerdialog-on-next-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!