I am using a ViewPager with a custom PagerFragmentAdapter that uses an internal list to provide fragments. I would like to add and remove fragments dynamically on settings changes.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new ServicePagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
I have tried to call again the setAdapter but I obtain an IllegalStateException (Can not perform this action after onSaveInstanceState).
How can achieve my purpose?
You don’t need to reset your
ServicePagerAdapterevery time. It’s enough to create and set it once inonCreate()method of yourActivity(or inonActivityCreated()method of yourFragment) and then you can simply calladd()method of your adapter to add new elements to it. But don’t forget to callnotifyDataSetChanged()after every addition to adapter.