Manak Kapoor
Manak Kapoor

Reputation: 982

ViewPager Fragments modifying UI

Hey I'm using a ViewPager with Fragments.

I'm attempting to modify the fragment's UI (such as remove images in imageviews to free up memory) when it's not visible, and re add images when its visible again.

I'm unable to find the proper way of doing this, as i'm not sure how to access the my fragment's view from setUserVisibleHint.

I've tried putting the view into a variable during onCreateView, but I get nullpointerexceptions for some odd reason.

What would be the right way to do this? Or is there anyway i could destroy fragments when they're not in view?

Upvotes: 2

Views: 1037

Answers (2)

Michel-F. Portzert
Michel-F. Portzert

Reputation: 1785

You don't have to remove views by yourself, each fragment view is automatically destroyed in the onDestroyView() method of Fragment when not visible anymore (no wonder you get a NullPointerException if you try to access the view when not visible). Then it is created again inside the onCreateView() method when the fragment is back and visible.

You may want to read the Fragment lifecycle for more information

Anyway, if you still want to access fragments to do whatever you want to their views, I suggest implementing this kind of code (I took from here) inside your FragmentPagerAdapter:

private Map<Integer, Fragment> mPageFragments = new HashMap<Integer, MyFragment>();

@Override
public Fragment getItem(int index) {
    Fragment myFragment = MyFragment.newInstance();
    mPageFragments.put(index, myFragment);
    return myFragment;
}

@Override
public void destroyItem(View container, int position, Object object) {
    super.destroyItem(container, position, object);
    mPageFragments.remove(position);
}

public MyFragment getFragment(int key) {
    return mPageFragments.get(key);
}

Then, inside a OnPageChangeListener on your ViewPager (for example), you can get back fragments and views using:

MyFragment fragment = adapter.getFragment(position);
if (fragment.getView() != null) {
   // ...
}

Upvotes: 0

Mark
Mark

Reputation: 5566

You can use 2 different adapters for View pager:

  • FragmentPagerAdapter
  • FragmentStatePagerAdapter

They both work in similar way. View pager keeps in memory only the current and neighbor views. When you are on page 5 - memory will be allocated for 4,5,6 Fragments. When you move to page 6: 4 is removed and 7 is added.

The main difference between two adapters is that FragmentPagerAdapter is destroying only the view of the fragment and the next time you get back to the fragment OnCreateView method is started. FragmentStatePagerAdapter is more memory friendly with a disadvantage of worse performance. It destroys the whole fragment and when you get back to it - view pager will invoke OnCreate and OnCreateView.

Upvotes: 6

Related Questions