Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager - onCreateView is not always called

I have a ViewPager with 10 pages. When I start the last (10th) page onCreateView() method of my fragment is called. When I swipe to the 9th page onCreateView() is called also. But when I back to the 10th page onCreateView() isn't called. What's wrong?

like image 392
Bakus123 Avatar asked Aug 29 '14 18:08

Bakus123


People also ask

What is called after onCreateView?

The onActivityCreated() method is called after onCreateView() and before onViewStateRestored() . onDestroyView() : Called when the View previously created by onCreateView() has been detached from the Fragment . This call can occur if the host Activity has stopped, or the Activity has removed the Fragment .

Is onCreate called before onCreateView?

The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView() .

What is ViewPager used for?

Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows. ViewPager is most often used in conjunction with android.

Is ViewPager deprecated?

This method may be called by the ViewPager to obtain a title string to describe the specified page. This method is deprecated. This method should be called by the application if the data backing this adapter has changed and associated views should update.


3 Answers

Try Extending FragmentStatePagerAdapter

like image 184
Vinay Avatar answered Nov 09 '22 23:11

Vinay


That is because a FragmentPagerAdapter keeps in memory every fragment. Hence, when you visit the first time the fragment, onCreate will be invoked but the second time Android will looking for in memory, so it not need invoke onCreate.

If you need run the code in OnCreate every time fragment is displayed, you should move it to getItem(int id)

See offical documentation: http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html

like image 38
Fran b Avatar answered Nov 10 '22 00:11

Fran b


Nothing is wrong. The ViewPager already has the page, and so it does not need to create it.

like image 26
CommonsWare Avatar answered Nov 09 '22 23:11

CommonsWare