Question

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);   
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top