Reputation: 25
I have an activity with 3 tabs/fragments, one of them now has a datepicker which opens on a button click. The date picker works but im confused as to how i can get the selected date back on the fragment class to auto load some data after the change?
It's as if i need some sort of onDateSet but on the fragment class where my button click is.
Please advice if you can, thanks:
Fragment1/Tab1:
On btn click open the date picker:
public void onClick(View v) {
switch (v.getId()){
case R.id.bFromDate:
DialogFragment picker = new DatePickerFragment();
picker.show(getActivity().getFragmentManager(), "datePicker");
break;
}
}
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 month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
}
}
Thank you..
Upvotes: 0
Views: 921
Reputation: 7070
You can set the target fragment while instantiating your DialogFragment
-
DialogFragment picker = new DatePickerFragment();
picker.setTargetFragment(this, <request_code>); // any number
picker.show(getActivity().getFragmentManager(), "datePicker");
And in your DialogFragment
whenever you want to send data back to the calling Fragment,
Intent intent = new Intent();
intent.putStringExtra("key_date", formattedDate);
getTargetFragment().onActivityResult(getTargetRequestCode(), <request_code>, intent);
And in your receiving fragment, implement onActivityResult()
to receive the data from the DialogFragment
.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Make sure fragment codes match up
if (requestCode == <request_code>) {
String date = data.getStringExtra("key_date");
...
}
Upvotes: 2