Thursday 25 September 2014

Safely delete fragment in viewpager

People tend to have multiple fragments when using viewpager, here is a good way to get rid of those fragments after you exit the current screen that has the viewpager.

in your onDestroy method:



  
  for (int i = 0; i < pagerCount; i++) {
       FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
       MyFragment f = (MyFragment) getSupportFragmentManager().findFragmentByTag(getFragmentTag(i));
       trans.remove(f).commitAllowingStateLoss();

  }
private String getFragmentTag(int position) {
        return "android:switcher:" + R.id.your_view_pageer_id + ":" + position;
    }
Hope this helps :)

No comments:

Post a Comment