I am trying to open a Dialogfragment from a Fragment. The dialogFragment has a Timepicker and I want to return the selected hour and minute from the timepicker to the calling fragment. How can I do this? I tried the below from the question but could not make it work. Can someone please give pseudo code for below solution(shown in end)
My code to show Dialog from fragment:
TimePickerFragment timepicker = TimePickerFragment.newInstance(1);
timepicker.show(getFragmentManager(), "timepickerfrag");
Code of the Dialogfragment:
public class TimePickerFragment extends DisplayDialogFragment implements View.OnClickListener {
private static final String ARG_PARAM1 = "param1";
private int mParam1;
private TimePicker time;
private Button bt1, bt2;
private TimePicker tm;
public static TimePickerFragment newInstance(int param1) {
TimePickerFragment fragment = new TimePickerFragment();
fragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public TimePickerFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_time_picker_scheduler, container, false);
bt1 = (Button) view.findViewById(R.id.sched_time_pck_btn_ok);
bt2 = (Button) view.findViewById(R.id.sched_time_pck_btn_cancel);
tm = (TimePicker) view.findViewById(R.id.sched_dialog_time_picker);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sched_time_pck_btn_cancel:
dismiss();
break;
case R.id.sched_time_pck_btn_ok:
dismiss();
break;
}
}
}
Receive result from DialogFragment
Use myDialogFragment.setTargetFragment(this, MY_REQUEST_CODE) from the place where you show the dialog, and then when your dialog is finished, from it you can call getTargetFragment().onActivityResult(getTargetRequestCode(), ...), and implement onActivityResult() in the containing fragment. It seems like an abuse of onActivityResult(), especially as it doesn't involve activities at all. But I've seen it recommended by official google people, and maybe even in the api demos. I think it's what g/setTargetFragment() were added for.