Reputation:
I have the below code in my app.
From my understanding I expect that after Main activity is loaded getItem
from Tab Adapter should be called with index: 1
as it is set as tab-1 .setTabListener(this), 1,true);
But instead of it getItem
gets called twice first with index: 0
and then index: 1
. Why is that can anyone explain?
//Main activity code:
@Override
protected void onCreate(final Bundle savedInstanceState) {
…
// Tabs Initilization
viewPager = (ViewPager) findViewById(R.id.TabHandler);
actionBar = getActionBar();
mAdapter = new TabsAdapter(getSupportFragmentManager());
actionBar.addTab(actionBar.newTab().setText(tabs[0])
.setTabListener(this), 0, false);
actionBar.addTab(actionBar.newTab().setText(tabs[1])
.setTabListener(this), 1,true);
actionBar.addTab(actionBar.newTab().setText(tabs[2])
.setTabListener(this), 2, false);
}
//And this inside the `Tab Adapter`
public class TabsAdapter extends FragmentPagerAdapter {
public TabsAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new ZeroViewFragment();
case 1:
return new OneViewFragment();
case 2:
return new TwoViewFragment();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
Upvotes: 1
Views: 527
Reputation: 2591
This is beacause the ViewPager
loads not only the visible fragment but the left and right fragments too. So in your case the visible fragment is #0, there is not left fragment and the right fragment is #1. The result is that fragments #0 and #1 are loaded. This behavior is implemented for performance reasons because this way the ViewPager
has the next fragment prepared and ready to be shown and there will be no lag when swiping between pages.
Upvotes: 0