I’ve been programming for android for approximately seven weeks. I’ve started on a application that use the template “Tabs + Swipe”, that was introduced in “IceCreamSandwich”(API level 14).
There are plenty question on stack-overflow concerning Fragments, but i haven’t been able to find a solutions for my specific problem.
My problem is that the template “Tabs + Swipe” has 1 FragmentActivity which instantiate 3 tabs and the autogenerated onCreate method look like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
I want to make 3 fragments, 1 for each tab. How should i inflate my tab1.xml, tab2.xml and tab3.xml layout from the different fragments classes? Should i use the getItem method from the the class “PagerAdapter extends FragmentPagerAdapter”?
@Override
public Fragment getItem(int i) {
// pseudo-code explanation
switch (i) {
case 0:
inflate tab1.xml;
case 1:
inflate tab2.xml;
case 2:
inflate tab3.xml;
}
return fragment;
}
It’s my first question here, so hope it’s to understand.
Thanx Michael
the getItem() method should return the fragment. So it should look like this: