我已经为 android 编程了大约七个星期。我已经开始使用模板“Tabs + Swipe”的应用程序,该模板是在“IceCreamSandwich”(API 级别 14)中引入的。
关于片段的堆栈溢出有很多问题,但我无法为我的具体问题找到解决方案。
我的问题是模板“Tabs + Swipe”有 1 个 FragmentActivity 实例化 3 个选项卡,自动生成的 onCreate 方法如下所示:
@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));
}
}
我想制作 3 个片段,每个选项卡 1 个。我应该如何从不同的片段类中扩展我的 tab1.xml、tab2.xml 和 tab3.xml 布局?我应该使用“PagerAdapter 扩展 FragmentPagerAdapter”类中的 getItem 方法吗?
@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;
}
这是我在这里的第一个问题,所以希望它能够理解。
感谢迈克尔