I created a DialogFragment
that has an EditText
, and when the user presses the EditText
there is a new DatePickerDialog
that suppose to pick a date from the user and then set it in the DialogFragment
. I am having a hard time to do so:
DialogFragment
. When I click ok/whatever I return to the activity.getActivity()
method. So how can I pass the date I picked back to the fragment that called the picker?Main Fragment
public class NewWorkoutItemFragment extends android.app.DialogFragment implements
View.OnClickListener {
private String mDate;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_workout_item, container, false);
//A lot of code
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.NewWorkout_date_et:
//Call to DatePickerDialog
DialogFragment pickDate = new DatePickerFragment();
pickDate.show(getFragmentManager(), "show");
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
}
DatePickerFragment
public class DatePickerFragment extends android.app.DialogFragment implements DatePickerDialog.OnDateSetListener {
@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);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String dateString = Integer.toString(dayOfMonth) +
"/" + Integer.toString(month+1) +
"/" + Integer.toString(year);
//note- Return dateString back to NewWorkoutItemFragment, using setmDate
}
}
The solution isn't about the datepickerdialog
at all. I had a switch-case in my fragment that manages the events of clicks. I accidentally forgot to put a break;
after the case which caused a flow to the other events (one of them was dismiss();
), and that's why the datepickerdialog also dismissed my fragment.