James James - 2 months ago 9
Android Question

How to Prevent Android FragmentStatePagerAdapter from Creating Neighboring Fragments

I am creating an Android app, and I have linked a

FragmentStatePagerAdapter
to a
TabBar
inside one of my
Activities
to allow users to slide from
Fragment
to
Fragment
. Each
Fragment
in this
Activity
is populated by a REST call, and if it fails, a
Dialog
will pop-up saying you should try and refresh your information (only the first time you view the
Fragment
). The problem I am having is that since
FragmentStatePagerAdapter
creates the neighboring
Fragments
to the
Fragment
you are currently on, it is creating the
Dialog
(s) of said
Fragments
prematurely (For example if you are on
Fragment
3, and
Fragment
4 prompts a
Dialog
, it will show on
Fragment 3
instead of
Fragment 4
). Is there a way to turn off the creation of neighboring
Fragments
using a
FragmentStatePagerAdapter
?

Thank You!

Answer

You can control the number of neighboring fragments that area created by calling setOffscreenPageLimit, but the minimum is 1.

Instead of creating your Dialogs in the fragments' onCreateView, I would do it setUserVisibleHint instead. That way the dialog is only created when you're certain that the user is on the page.

Comments