saleh sereshki
saleh sereshki

Reputation: 2532

Is onCreateView() event fired every time we create a new Fragment?

I have a viewpager which has 5 pages.
In the getView() method in the Adapter of this ViewPager I wrote:

MyFragment fragment =new MyFragment(myObject, context);
return fragment;

Now, it works correctly.
But, in a particular situation, the onCreateView() event of MyFragment is not fired.

When I debug my code it goes to the Fragment constructor, but it does not enter the onCreateView() method.

Upvotes: 0

Views: 577

Answers (2)

SuperFrog
SuperFrog

Reputation: 7674

Instantiating a fragment doesn't invoke its lifecycle callbacks, these methods will be called only after you commit the fragment transaction, e.g.:

  FragmentTransaction transaction = getFragmentManager().beginTransaction();
  MyFragment fragment = new MyFragment(myObject, context);
  transaction.add(fragment , "some_tag");
  transaction.commit();

Upvotes: 1

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

Your fragment's OnCreateView method is called once when the fragment is created for the first time. But when you swipe through your ViewPager, the fragment is hidden, not destroyed. So when you swipe back to your fragment, onCreateView is not called because the fragment is already created.

Upvotes: 0

Related Questions