How to pass a listener from a fragment to DialogFragment

I have a Fragment that show DialogFragment . DialogFragment creates and displays the TimePickerDialog dialog.

I want the calling fragment to implement the imePickerDialog.OnTimeSetListener . but I don’t know how to pass this listener to the Called (The DialogFragment) fragment ..

I found the following code that passes to the listener from ACTIVITY to DialogFragment .

 @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; // This error will remind you to implement an OnTimeSetListener // in your Activity if you forget try { mListener = (OnTimeSetListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnTimeSetListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); // Create a new instance of TimePickerDialog and return it return new TimePickerDialog(getActivity(), mListener, hour, minute, true); } 

How to pass it from Fragment ?

+3
source share
1 answer

Can't you just use getTargetFragment and setTargetFragment?

And then first check if targetFragment is an instance of your listener:

if (getTargetFragment () instanceof OnTimeSetListener) {mListener.updateTime (); }

+1
source

Source: https://habr.com/ru/post/1272366/


All Articles