简体   繁体   中英

When should a Fragment's onActivityCreated be called?

I have a few Fragments in a ViewPager, and I've found the Fragment's onActivityCreated and onCreateView are both being called on the page before I expect.

For example, when the ViewPager transitions from page 2 to 3, then the Fragment at page 4's onCreateView and onActivityCreated are being called.

I'm intending to initiate a network request in onActivityCreated but it is starting one screen too soon. According to the Android docs , onActivityCreated is called "when the fragment's activity has been created and this fragment's view hierarchy instantiated." which leads me to believe I'm using the method correctly.

For smooth loading of data view pager will load the fragments in advance. 1. If you are at 1st position(first fragment),so its automatically loads the next 2 fragments 2.Or if you are at 2 or later,then it will load previous one fragment and next fragment

ViewPager loads the next fragment for smooth transition between fragments, and that's why your next fragment's onCreate() , onCreateView() and onResume() is getting called. So, add onPageChangeListener on your viewPager like:

yourViewPager.addOnPageChangeListener(new OnPageChangeListener{
    @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
        @Override
        public void onPageSelected(int position) {
        switch(position){
            //your code for network operation
        }
    }
    @Override
        public void onPageScrollStateChanged(int state) {}

});     

As others have mentioned, this is done for smooth loading of data in a view pager. What you can do though is call your code in onAattach() or when your fragment is visible to the user in onStart() . Android docs gives more details on lifecycle methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM