0

I am using FragmentActivity and ViewPager to show several fragments.I want to show different fragment each time according to the intent passed to the FragmentActivity.But the problem is when I use setCurrentItem() after setAdapter(), the first Fragment will be always created,how can I avoid this?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.container_page);

    mDemoCollectionPagerAdapter = new FragmentPageAdapter(
            getSupportFragmentManager());

    mViewPager = (ViewPager)findViewById(R.id.pager);   

    mViewPager.setAdapter(mDemoCollectionPagerAdapter);

    Intent intent = getIntent();
    int whichFragment = intent.getIntExtra(Constants.EXTRA_WHICH_FRAGMENT, 0);

    mViewPager.setCurrentItem(whichFragment, false);
    setActionBarTitle(whichFragment);

    mViewPager.setOnPageChangeListener(this);   
}
Paparika
  • 137
  • 1
  • 12

2 Answers2

0

The app may be spending some time to retrieve your extra so he inflates your first fragment.

Try to put this before setAdapter():

Intent intent = getIntent();
int whichFragment = intent.getIntExtra(Constants.EXTRA_WHICH_FRAGMENT, 0);

Then, right after setAdapter, set the current item.

Murillo Ferreira
  • 1,423
  • 1
  • 16
  • 31
  • Sorry but let me see if I understand, you want your fragment requested by the intent to be created first instead of the first fragment right? I'm assuming this is for performance reasons. Had you tried adapter.setPrimaryItem (container, position, object) ? – Murillo Ferreira Jan 26 '14 at 12:36
  • I have 3 buttons in another Activity, when I press one of them, FragmentActivity will be created and show different fragment,and yes there is performance issue, the first fragment has heavy work to do, so when 2nd fragment is requested, a lot of time is spending on preparing 1st fragment.But it seems that the system preload other fragments for better user experience(when swipe between fragments), so maybe I should try to optimize the 1st fragment? – Paparika Jan 28 '14 at 03:47
0

You can remove preceding Fragments from the adapter..and add them afterwards..

Don't forget to call notifyDataSetChanged() after you add other fragments..Otherwise you will get an exception

Also you might need to override this method getItemPosition() in the adapter to return incremented positions for all fragments.

simekadam
  • 7,334
  • 11
  • 56
  • 79