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” ?
First, you’re asking for fragments based on the ID. The ID
R.id.pageris just some random number that’s linked to whateverR.id.pageris. 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
ViewPagerretrieves the current page plus any other page that is in the immediate vicinity that it does not already have. This means that it’s callinggetItem()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 seePOSITION 2because the ViewPager needs to createPOSITION 2in preparation of the next swipe. If you were to jump to item 4, you’ll seePOSITION 2 POSITION 3 POSITION 4.