2

It is surprisingly difficult to get the current fragment when using either of the pager adapters. With the FragmentPagerAdapter, however, you can look for a fragment with the tag "android:switcher:" + viewId + ":" + id.

Unfortunately, there does not seem to be a standard tag for the FragmentStatePagerAdapter. A related question provided a couple answers which suggested manually keeping a cache of the fragments, which were noted as being inadequate when doing a rotation: the underlying adapter stores state in a bundle and restores it when it is created, causing any simple caching solution to fail.

Community
  • 1
  • 1
Shawn Lauzon
  • 6,234
  • 4
  • 35
  • 46

1 Answers1

0

I found a better solution. getCurrentFragment() cannot be implemented correctly from what I can tell.

My code was previously launching a dialog and then calling back to the Activity which was stored by the dialog at onAttach. The Activity then needed to find the correct Fragment, which was problematic.

The correct solution is to first call setTargetFragment() on the new dialog fragment:

SelectProblemDialogFragment f = SelectProblemDialogFragment.newInstance(args);
f.setTargetFragment(this, 0);
f.show(getFragmentManager(), "select_problem_dialog_fragment");

and then in onAttach(), simply use that as the listener.

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);

    try
    {
        mListener = (SelectProblemDialogListener) getTargetFragment();
        if (mListener == null)
        {
            mListener = (SelectProblemDialogListener) activity;
        }
    } catch (ClassCastException e)
    {
        throw new ClassCastException("Must implement SelectProblemDialogListener");
    }
}
Shawn Lauzon
  • 6,234
  • 4
  • 35
  • 46