In portrait mode, my ViewPager
has 3 fragments A, B, C but in landscape mode, it has only 2 fragments A and C. So I create 2 FragmentStatePagerAdapter
s for each mode. The problem is when screen orientation changed, ViewPager
restores and uses previous fragments of old orientation. For example, when change orientation from portrait to landscape, ViewPager
now shows 2 fragments A, B instead of A and C. I know why this happen but can't find a good solution for this.
My current workaround is to use different ids for ViewPager
(eg: id/viewpager_portrait for portrait and id/viewpager_landscape for landscape layout) to prevent from reusing fragments but this cause me a memory leak because old fragment will not be destroyed and still be kept in memory.
I have tried some workaround like call super.onCreate(null) in activity's onCreate
, or remove fragments of ViewPager
in activity's onSaveInstanceState
but they all makes my app crash.
So my question is how to avoid reusing one or many fragments in FragmentStatePagerAdapter
when orientation changed?
Any helps will be appreciated. Thank in advance.
onSaveInstanceState
and avoid callingsuper.onSaveInstanceState
in that method. This would prevent theFragment
from getting saved. – Araroba