Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: limit fragments loading with a viewPager

I have 3 fragments that are managed by an FragmentPagerAdapter, set to a viewPager.

I want to load fragments one by one, but when the onCreate method of FragmentActivity is executed, the 2 first fragments are executed (onCreateView method).

I have tried to limit fragments loading with the setOffscreenPageLimit method but nothing change.

mPagerAdapter =  new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
pager = (ViewPager) super.findViewById(R.id.tabviewpager);
pager.setOffscreenPageLimit(0);
pager.setAdapter(this.mPagerAdapter);

Thank you for your help .

like image 702
johann Avatar asked Nov 26 '12 07:11

johann


People also ask

What is ViewPager2 in Android?

ViewPager2 uses FragmentStateAdapter objects as a supply for new pages to display, so the FragmentStateAdapter will use the fragment class that you created earlier. Create an activity that does the following things: Sets the content view to be the layout with the ViewPager2 .

How does ViewPager2 work?

So a Viewpager is an android widget that is used to navigate from one page to another page by swiping left or right using the same activity. So when we use Viewpager, we can add different layouts in one activity and this can be done by using the fragments.

How to create ViewPager adapter in Android?

Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class.


1 Answers

The minimum for OffscreenPageLimit is set to 1 in the ViewPager source code:

private static final int DEFAULT_OFFSCREEN_PAGES = 1;
....
public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {
        Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    if (limit != mOffscreenPageLimit) {
        mOffscreenPageLimit = limit;
        populate();
    }
}
like image 91
antew Avatar answered Sep 28 '22 07:09

antew