I have a fragment which contain an EditText when I click on that EditText a DatePicker Dialog appears to select date.
FragmentFile
public c
Updated code
FragmentFile
public class FirstFragment extends Fragment implements DatePickerDialogFragmentEvents{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
EditText editText = (EditText) view.findViewById(R.id.visitDateFiled);
editText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogFragment picker = new DatePickerFragment();
picker.setDatePickerDialogFragmentEvents(FirstFragment.this); //Changed
picker.show(getFragmentManager(), "Date Picker");
}
});
return view;
}
//This is where you will get selected date value
@Override
public void onDateSelected(String date) {
String selectedDate = date;
}
}
DialogFragment
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
//Interface created for communicating this dialog fragment events to called fragment
public interface DatePickerDialogFragmentEvents{
void onDateSelected(String date);
}
DatePickerDialogFragmentEvents dpdfe
public void setDatePickerDialogFragmentEvents(DatePickerDialogFragmentEvents dpdfe){
this.dpdfe = dpdfe;
}
@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 day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = sdf.format(c.getTime());
dpdfe.onDateSelected(formattedDate); //Changed
}
}
So i created an interface named DatePickerDialogFragmentEvents in your dialogfragment class and implemented that in caller fragment. From caller fragment when you create a instance of dialogfragment, set DatePickerDialogFragmentEvents instance of fragment by using setDatePickerDialogFragmentEvents method of dialog fragment class.