-1

In all the example of the use of fragments seen I see a problem.

The my idea is that the onCreate function of each fragment should be called after swipe so before the creation of the next page.

In all the case the onCreate of fragment 1 and 2 is called when you must display page 1 and after the onCreate of fragment 3 is called when you must display page 2.

Why this problem ?

  • onCreate is called based on the lifecycle of a fragment. So it all depends on how you're using your fragments. Can you please add some code? – Gregorio Palamà Jan 16 '19 at 14:07

2 Answers2

0

The my idea is that the onCreate function of each fragment should be called after swipe so before the creation of the next page.

From "swipe" I assume you are hosting fragments in a ViewPager. It has an offscreen page limit that controls how many fragments are pre-created on each side of the current page. By default it's 1, so at page 0 the page 1 fragment is also created.

If you really want fragment onCreate()s to fire exactly when the fragment becomes visible, set the offscreen page limit to 0. Setting the page limit to 0 does not work as the default minimum is 1.

If you're just interested to detect when the fragment becomes visible, you can hook up to setUserVisibleHint().

laalto
  • 150,114
  • 66
  • 286
  • 303
  • No changes with this modification @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "getItem - main - start: "); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.pager); actionBar = getActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); viewPager.setOffscreenPageLimit(0); viewPager.setAdapter(mAdapter); – andrea ciuffoli Jan 16 '19 at 14:33
  • If I change it to 3 I can create all the page at the begin (0,1,2 and 3) but if I set to 0 I always create 0 and 1 at the same time. – andrea ciuffoli Jan 16 '19 at 14:43
  • Yes, https://stackoverflow.com/questions/10073214/viewpager-setoffscreenpagelimit0-doesnt-work-as-expected – laalto Jan 16 '19 at 14:57
0

ok solved with this

private boolean isViewShown = false;
private boolean isFragmentLoaded = false;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser   && !isFragmentLoaded) {
        isViewShown = true;
        TableLayout table = (TableLayout)getActivity().findViewById(R.id.table);
        display_album(table);

        isFragmentLoaded = true;
    } else {
        isViewShown = false;
    }
}