2

I'm using this line to get the current fragment displayed :

Item myFragment = (Item) getSupportFragmentManager().findFragmentById(R.id.pager);

Here is an example of my ViewPager

| A | B | C | D | E | F |

The first fragment displayed is A, but myFragment is B When I go to B, myFragment = B ... When I go to F, myFragment = E You can see the code here : -> TabsActivity.java

Someone has already got this problem ? Why there is a shift between the fragment displayed and the value of myFragment ?

Thanks

[EDIT] I add a Log() Now here is a part of my TabsActivity

class TabsAdapter extends FragmentStatePagerAdapter  {

    public TabsAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Log.e("POSITION", position + "");
        return Item.newInstance(CONTENT.get(position % CONTENT.size()));
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return CONTENT.get(position % CONTENT.size());
    }

    @Override
    public int getCount() {
      return CONTENT.size();
    }
}

And when I start my application my logger display : POSITION 0 POSITION 1

Is it normal ? It shouldn't be only "POSITION 0" displayed ? And when I slide, "POSITION 1" ?

Simon
  • 14,407
  • 8
  • 46
  • 61
guillaume
  • 1,638
  • 5
  • 24
  • 43

1 Answers1

4

First, you're asking for fragments based on the ID. The ID R.id.pager is just some random number that's linked to whatever R.id.pager is. In the code provided, you're not assigning an ID to any of your Fragments, so the fact that you're getting anything is lucky.

If you want to retrieve a Fragment from a Viewpager, then you need to follow the criteria answered in this question: Update data in ListFragment as part of ViewPager

Second, the reason you're getting "POSITION 0 POSITION 1" is because the ViewPager retrieves the current page plus any other page that is in the immediate vicinity that it does not already have. This means that it's calling getItem() on the current page, the previous page, and the next page. At position 0, there is no previous page, but there is a next page. If you swipe over, you'll only see POSITION 2 because the ViewPager needs to create POSITION 2 in preparation of the next swipe. If you were to jump to item 4, you'll see POSITION 2 POSITION 3 POSITION 4.

Community
  • 1
  • 1
DeeV
  • 35,865
  • 9
  • 108
  • 95
  • Now it's clear for the second part ;) Thanks And I solve my problem by recording index when I instanciate my fragment. Like here [link]http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html – guillaume Oct 31 '12 at 20:01