Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload fragment's view in ViewPager on first run

I'm using ViewPager that holds 3 fragments, each fragment loads a list. The problem is when the application runs for the first time and I swipe to the next fragment, this fragment needs sometime to load (about 2 seconds) before its view is visible. This is a very weird behavior. All I want is once the app has started, all fragments in ViewPager should be ready for user so when they swipe through fragments, there's no wait time. How can I do that?

like image 876
Duc Le Avatar asked Aug 20 '13 17:08

Duc Le


People also ask

Can I use ViewPager with views not with fragments?

yes...you can use View instead of Fragment in viewpager.

How do I refresh ViewPager fragments?

Using the ViewPager. OnPageChangeListener is the correct way to go, but you will need to refactor your adapter a bit in order to keep a reference to each Fragment contained in the FragmentPagerAdapter. Then, instead of creating a new Fragment, use the one contained in the adapter: mViewPager.

When should I use ViewPager?

ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in app. It is a widget found in the support library. To use it you'll have to put the element inside your XML layout file that'll contain multiple child views.


1 Answers

Just call setOffscreenPageLimit() in onCreate() (after initializing ViewPager). The OffscreenPageLimit sets the number of pages that should be retained to either side of the current page (in your case 2). With this all of your fragments will be instantiate.

(An other (highly recommended) possibility is to increase the performance of your lists or listadapters, because a loading time of 2 seconds doesn't sound good)

like image 193
Namenlos Avatar answered Oct 06 '22 23:10

Namenlos