How to stop refreshing fragments on tab change in Android

How to stop refreshing fragments on tab change in Android

Problem:

How to stop refreshing fragments on tab change You can add multiple fragment tabs in viewpager. But when you swipe tabs, the transition quite slow because of the destruction of the fragment view, which is refreshing during the swipe operation.

The viewpager does not create all pages at a time. By default, viewpager only creates the current page as well as the off-screen pages to the left and right of the current page.

This article gives you a solution for How to stop refreshing fragments on tab change problem.

For example

I have added 5 pages (fragments) in viewpager means n = 5. Viewpager loads a maximum of 3 pages at first time load, the one displaying (n), previous (n-1) and next (n+
1) pages are in resumed.

5 pages will be loaded while you move from first to last: (where X is a loaded page and 0 is a destroyed page.)

XX000 -> XXX00 -> 0XXX0 -> 00XXX -> 000XX

Solutions

          If you want to stop refreshing fragment then add below code.

ViewPager view_pager = (ViewPager) view.findViewById(R.id.pager); 
view_pager.setOffscreenPageLimit(5);

In above example, I have n=5 (0 to 4), So, When first time viewpager will load all fragments, then it won’t destroy on swipe.

It is work like this:

XXXXX -> XXXXX -> XXXXX -> XXXXX -> XXXXX

All pages are created (X pages) at one time and resumed, not refreshed while swipe.

If you have N numbers of pages then add below line in your code:

view_pager.setOffscreenPageLimit(N);

Use this viewpager to keep all of them in memory and resumed (not create and destroy). But you need MEMORY MANAGEMENT. For example, there are many items with images, videos and animations. If you cache all of them, this will result with an OutOfMemoryError.

ViewPager require atleast  1 off screen pages, so you cannot set offscreen page limit to 0. By default, off screen limit is 1. If you set limit as 0 then you will get a warning like following:

Requested off screen page limit 0 too small; defaulting to 1

It’s because viewpager is based on concept of keep ready to next page to be loaded.

The conclusion for this article is if you have a small amount of pages (fragments) you may get a better performance by creating them all at once and you can also use setOffscreenPageLimit(int limit) to set the number of pages that will be created and retained. But you also need to take care of Memory need if there are more graphics uses.

Enjoy Coding…

Thank you.