我为 Android 编程已经大约七个星期了。我已经开始开发一个使用“Tabs + Swipe”模板的应用程序,该模板是在“IceCreamSandwich”(API 级别 14)中引入的。
关于 fragment 的堆栈溢出有很多问题,但我无法找到针对我的具体问题的解决方案。
我的问题是模板“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 个 fragment ,每个选项卡 1 个。我应该如何从不同的 fragment 类中扩充我的 tab1.xml、tab2.xml 和 tab3.xml 布局?我应该使用“PagerAdapter extends 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;
}
这是我的第一个问题,所以希望它能理解。
谢谢迈克尔
最佳答案
getItem() 方法应返回 fragment 。所以它应该看起来像这样:
@Override
public Fragment getItem(int i) {
// pseudo-code explanation
Fragment fragment;
switch (i) {
case 0:
fragment = new FragmentTab1() // which inflates tab1.xml in its onCreateView() method;
case 1:
fragment = new FragmentTab2(); //etc.
case 2:
fragment = new FragmentTab3();
}
return fragment;
}
关于android - 如何在 FragmentActivity 中膨胀不同的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13973614/