in my activity i have simple FrameLayout
widget and i'm trying to attach simple fragment to that by replace
and using some fragment into nested fragment but i get Fragment already added
error when i try to add some fragment in nested fragment, for example this is my activity:
public class MainActivity extends AppCompatActivity {
private CarouselFragment carouselFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (savedInstanceState == null) {
initScreen();
} else {
carouselFragment = (CarouselFragment) getSupportFragmentManager().getFragments().get(0);
}
...
}
private void initScreen() {
carouselFragment = new CarouselFragment();
final FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, carouselFragment)
.commit();
}
}
and nested fragment is CarouselFragment
class :
in this fragment i'm trying to set some other fragment to adapter to use them
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_carousel, container, false);
ButterKnife.bind(this, view);
context = getContext();
viewPager = (ViewPagerCustomDuration) view.findViewById(R.id.vp_pages);
adapter = new CarouselViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new FragmentA());
adapter.addFragment(new FragmentB());
viewPager.setAdapter(adapter);
viewPager.setPageMargin(50);
viewPager.setOffscreenPageLimit(3);
viewPager.setScrollDurationFactor(4);
viewPager.setOffscreenPageLimit(1);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
and then this is my adapter:
public class CarouselViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public CarouselViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
mFragmentList.add(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
mFragmentList.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return mFragmentList.get(position);
}
}
Problem is this lines of codes:
adapter.addFragment(new FragmentA());
adapter.addFragment(new FragmentB());