Android : How switch statement in FragmentPagerAdapter's getItem() work?

on Tuesday, September 16, 2014


Have a look at this code :



@Override
public Fragment getItem(int index){

Log.i("Tab position", String.valueOf(index));
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}

return null;
}

@Override
public int getCount() {
// TODO Auto-generated method stub

return 3;
}


ViewPager works fine but how ?




  1. When i start my app i get following Logcat with TabPosition 0 and 1:


    09-16 15:28:20.353: I/Tab position(2737): 0 09-16 15:28:20.372: I/Tab position(2737): 1




  2. Now when i select second Tab or swipe to second page i get following Logcat with TabPosition 2:


    09-16 15:28:29.072: I/Tab position(2737): 2




  3. when i select third Tab or swipe to third page then there is no Logcat and TabPosition not printed :




My confusion is I know that index returned by getItem() is not a position of current selected Page or Tab but it is a position of pages that need to be rendered.


But if this is a case then how switch statement returns correct Fragment although index is not correct one.


For example :


Initially there are two indexes returned by getItem() 0 and 1, now how switch statement decides to select 0 or 1.


I hope you understand question.


0 comments:

Post a Comment