user5448913
user5448913

Reputation:

Catch DatePicker selection from calling Fragment

I have implemented a DatePicker via an ImageView in a Fragment.

@NonNull
@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);
}

// Called when the user presses "OK" on the DatePicker
@Override
public void onDateSet(android.widget.DatePicker datePicker, int i, int i1, int i2) {
    // Do something with the date chosen by the user
    String date = datePicker.getDayOfMonth() + "-" + datePicker.getMonth() + "-" + datePicker.getYear();       
}

I wish to catch a date selection in my calling Fragment that calls the DatePicker like such:

public class APD extends Fragment {

  [...]
   public void showDatePickerDialog() {
       DatePicker datePicker = new DatePicker();
       datePicker.show(getActivity().getSupportFragmentManager(), "datePicker");
   }

   calendar_image.setOnClickListener(new View.OnClickListener() {
           @Override
              public void onClick(View view) {
               showDatePickerDialog();
           }
       });
   [...]
}

How can that be achieved?

Upvotes: 0

Views: 53

Answers (1)

Abhishek Singh
Abhishek Singh

Reputation: 9188

You can catch date directly on fragment... see this code

String date;
ImageView ib=(ImageView)findViewByID(your id);
ib.setOnClickListener(new View.OnClickListener(){
 @Override
    public void onClick(View v) {
           int mYear, mMonth, mDay;
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);
    DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            date=dayOfMonth + "/" + (month + 1) + "/" + year;
        }
    }, mYear, mMonth, mDay);
    //for setting minimum date for selection
    datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis()); //optional for setting min date
    datePickerDialog.show();
    }
}

Upvotes: 1

Related Questions