我使用一个FragmentPagerAdapter来管理3个片段。
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
Fragment fragment = new Fragment();
switch (position) {
case 0:
return fragment = new Latest();
case 1:
return fragment = new MySets();
case 2:
return fragment = new MyPictures();
default:
break;
}
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
//SET TITLE OF TABS
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1_latest).toUpperCase(l);
case 1:
return getString(R.string.title_section2_mysets).toUpperCase(l);
case 2:
return getString(R.string.title_section3_allpictures).toUpperCase(l);
}
return null;
}
}所有框架都扩展了碎片。要处理单击事件和自定义布局,我使用扩展BaseAdapter的适配器。我的目标是通过另一个片段替换片段2。我必须用FragmentTransaction添加所有片段来替换它们,这是正确的吗?
但是我如何动态地添加片段来使用FragmentTransaction呢?是否有方法在getItem(int位置)添加它们,还是这样做是错误的?
发布于 2013-11-13 17:33:40
编辑
如果应用程序一启动就需要片段,那么上面在getItem()中使用的方法是可以的,您不需要在那里进行事务处理。
如果您希望稍后替换该片段,只需使用片段中的getSupportFragmentManger和事务。
NewFragment newFrag = new NewFragment();
FragmentTransaction transaction = getActivity()
.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.your_fragment_container_id, newFrag);
transaction.addToBackStack(null);
transaction.commit();https://stackoverflow.com/questions/19959625
复制相似问题