34

I have a viewpager with at least 3 fragments. If the user inputs data into A, then B, then C and goes back to A that data is lost from A.

I think I read somewhere that this has to do with memory management and since fragments only connect to or store adjacent fragments it's killing A when I get too far away. However I wish to retain the life of each fragment even were I to have >3.

How can I tell the viewpager to never kill a fragment unless explicitly directed?

Steven Akerfeldt
  • 629
  • 1
  • 7
  • 15

1 Answers1

85

use

setOffscreenPageLimit(int limit) 

on the ViewPager object.

From the documentation:

[It set]s the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Marcin S.
  • 11,161
  • 6
  • 50
  • 63
  • 1
    thanks a lot it is really helpful, I had 6 tabs and I wanted to maintain data of my first fragment and spent 2 days for it :) . – Antarix Apr 29 '14 at 05:16
  • This really helps. My fragments were losing states too. Any other tips you'd like to suggeat or anything I should keep in mind while using this property ? – Zen Jun 08 '14 at 07:51
  • 1
    Note that if you want to do the opposite and make sure your fragments are killed and restored according to the lifecycle, this will not help, because the [minimum `limit` is `1`](https://stackoverflow.com/a/10073916/11683) meaning at least 3 fragments are kept alive at all times. – GSerg Nov 26 '19 at 09:34