Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and removing fragments dynamically in ViewPager

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?

like image 636
Matroska Avatar asked Nov 05 '22 12:11

Matroska


1 Answers

You don't need to reset your ServicePagerAdapter every time. It's enough to create and set it once in onCreate() method of your Activity (or in onActivityCreated() method of your Fragment) and then you can simply call add() method of your adapter to add new elements to it. But don't forget to call notifyDataSetChanged() after every addition to adapter.

like image 170
HitOdessit Avatar answered Nov 11 '22 07:11

HitOdessit