I have a DialogFragment which opens another DialogFragment that implements a DatePicker, I want to pass the date from the DatePicker back to the previous DialogFragment and display it on an EditText. I found a way to pass the date back to the main activity, but I cant find a way to pass it back to the previous DialogFragment. Please Help.
I used the example here to add the DatePicker: https://neurobin.org/docs/android/android-date-picker-example/
This is the classes in my code: MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new MyDialogFragment();
newFragment.show(getSupportFragmentManager(), "DialogFragment");
}
});
}
MyDialogFragment
public class MyDialogFragment extends DialogFragment {
EditText edTo;
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.popup, container, false);
getDialog().setTitle("Set Date Range");
edTo = (EditText) rootView.findViewById(R.id.etDateTo);
edTo.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
return false;
}
});
return rootView;
}
}
DatePickerFragment public 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);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// Do something with the date chosen by the user
EditText etDateTo= (EditText) getActivity().findViewById(R.id.tv);
etDateTo.setText("Year: "+year+" Month: "+monthOfYear+" Day: "+dayOfMonth);
}
}
This is MyDialogFragment which opens the DatePicker enter image description here
EventBus solved the problem for me. I used the example from this link incasae anyone faced the same issue. http://www.cardinalsolutions.com/blog/2015/02/event-bus-on-android Thank you,