Search code examples
androiddatepicker

Two Date Picker fragments - how to edit date separately?


I was following the date picker Android tutorial. Unfortunately, after doing it, I realized it applies only to one of my text fields and to be honest, I have no idea how to apply it to the other one, DateEdit2. That is, clicking on either DateEdit1 or DateEdit2 I edit DateEdit1. I understand this comes from the function of setting the date, but any attempt to change or pass the button as argument causes error, as these methods cannot be edited this way. Any ideas?

here is the code:

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

    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);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            DateEdit1.setText(DateEdit1.getText() + " " + day + "/" + (month + 1) + "/" + year);
        }
    }

Thank you in advance, John


Solution

  • Make a global public boolean isDateEdit1; in activity.

    In the onClickListener from DateEdit1, before calling showTruitonDatePickerDialog(View v), set isDateEdit1 = true;.

    In the onClickListener from DateEdit2, before calling showTruitonDatePickerDialog(View v), set isDateEdit1 = false;.

    Then, in the onDateSet:

        public void onDateSet(DatePicker view, int year, int month, int day) {
            if(getActivity.isDateEdit1){
              DateEdit1.setText(""+day + "/" + (month + 1) + "/" + year);
              return;
            }
            DateEdit2.setText("" + day + "/" + (month + 1) + "/" + year);
        }